Reputation: 4915
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
Upvotes: 6
Views: 14640
Reputation: 292355
string hexColor = "#B5C7DE";
Color color = ColorTranslator.FromHtml(hexColor);
Upvotes: 7
Reputation: 22016
I would use the color translator as so:
var color = ColorTranslator.FromHtml("#FF1133");
Hope this helps.
Upvotes: 10
Reputation: 17691
You can use the Color.FromArgb method:
Label1.BackColor = Color.FromArgb(0xB5C7DE);
Upvotes: 0
Reputation: 89152
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.
Upvotes: 0