How to dynamically change color in C # to hexadecimal value?

I know how to set BackColor dynamic control in C # to a named color using an expression like Label1.BackColor = Color.LightSteelBlue; (using System.Drawing;)

But how to convert the hexadecimal value to System.Color, i.e. Label1.BackColor = "# B5C7DE

+6
user-interface c #
source share
4 answers

I would use a color translator like this:

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

Hope this helps.

+9
source share
 string hexColor = "#B5C7DE"; Color color = ColorTranslator.FromHtml(hexColor); 
+7
source share
 Color.FromArgb(0xB5C7DE); 

or if you want to parse a 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 simply returns the default value if it cannot parse s. You can simply throw an exception if you prefer to handle the exceptions yourself.

0
source share

You can use the Color.FromArgb method:

 Label1.BackColor = Color.FromArgb(0xB5C7DE); 
0
source share

All Articles