Get System.Drawing.Color from RGB HTML color

Back to some real content here!

Maybe you already know about this, but as I still often see static method like GetColorFromHTML() in companies static class, it could be a good reminder.

The idea is when you want to set a color in code, like GridView1.ForeColor = "#FFCC66", but this do not work because the property is of type System.Drawing.Color.

You don't need to create a convert method as there is already such a method in the Framework, but the location is not obvious.
First I would have checked for System.Drawing.Color.FromHTML() as there is already a System.Drawing.Color.FromArgb(), but no, it is not there. Instead you have to look in System.Drawing.ColorTranslator.

Convert a RGB color to System.Drawing.Color:

C#:
System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");

VB:
Dim col As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#FFCC66")

 

Convert a System.Drawing.Color to RGB string:

C#:
String sHtmlColor = System.Drawing.ColorTranslator.ToHtml(col);

VB:
Dim sHtmlColor As String = System.Drawing.ColorTranslator.ToHtml(col)

2 Comments

Comments have been disabled for this content.