ASP.NET/C#: Convert HTML Colors to System.Drawing.Color

HTML colors come in all sorts of flavors: hexadecimal (#0066ff), named colors (e.g. LightSkyBlue…here’s the link).

Many people may be very comfortable with working with HTML colors, so if you’re in C# and needing to get the .Net equivalent, you can translate directly from HTML colors with System.Drawing.ColorTranslator.FromHtml(). Here’s the usage:

System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("Red");
or
System.Drawing.ColorTranslator.FromHtml("#ff0000");

Controls require the System.Drawing.Color type:

TextBox t = new TextBox();
t.BackColor = System.Drawing.Color.Red;

Also useful is System.Drawing.ColorConverter. Here’s the MSDN link for that. But working from the HTML colors may be more familiar to you.

Popularity: 13%

Tags:
Filed under: ASP.NET/C#

Leave a Reply