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)

Published Wednesday, October 31, 2007 9:40 PM by pluginbaby
Filed under: ,

Comments

Thursday, November 1, 2007 4:36 AM by Mark Smith

# re: Get System.Drawing.Color from RGB HTML color

There is a Color.FromName method you can use e.g.

System.Drawing.Color.FromName("#FFCC66")

Thursday, November 1, 2007 10:02 AM by Blake Niemyjski

# re: Get System.Drawing.Color from RGB HTML color

Good find :)