views:

1015

answers:

4

I know how to set a control's BackColor dynamically in C# to a named color with a statement such as Label1.BackColor = Color.LightSteelBlue; ( using System.Drawing; )

But how do I convert a hex value into a System.Color , ie Label1.BackColor = "#B5C7DE

A: 
Color.FromArgb(0xB5C7DE);

or, if you want to parse the string

private Color ParseColor(string s, Color defaultColor)
{
    try
    {
        ColorConverter cc = new ColorConverter();
        Color c = (Color)(cc.ConvertFromString(s));

        if (c != null)
        {
            return c;
        }
    }
    catch (Exception)
    {
    }
    return defaultColor;
}

This function just returns the default if it can't parse s. You could just let the exception through if you'd rather handle exceptions yourself.

Lou Franco
+4  A: 
string hexColor = "#B5C7DE";
Color color = ColorTranslator.FromHtml(hexColor);
Thomas Levesque
A: 

You can use the Color.FromArgb method:

Label1.BackColor = Color.FromArgb(0xB5C7DE);
heavyd
+4  A: 

I would use the color translator as so:

var color = ColorTranslator.FromHtml("#FF1133");

Hope this helps.

Richard