Converting a Hexadecimal Color to a System.Drawing.Color Object

Please note this is source from an excellent post at AKXL Labs here – Im just putting up my (minor) modded version for my own future reference. All credit to AKXL Labs!

protected int Hex(string hex)
{
    return (HexStrToBase10Int(hex));
}

protected int HexStrToBase10Int(string hex)
{
    int base10value = 0;

    try
    {
        return (Convert.ToInt32(hex, 16));
    }
    catch
    {}

    return base10value;
}

protected Color HTMLHexToColor(string hex)
{
    hex = hex.Replace("#", "");

    if (hex.Length != 6) return (Color.Black);

    string r = hex.Substring(0, 2);
    string g = hex.Substring(2, 2);
    string b = hex.Substring(4, 2);

    return (Color.FromArgb(Hex(r), Hex(g), Hex(b)));
}

Usage:

private void enableTextBox(string txbname, bool p)
{
    TextBox txb = ((TextBox) FindControl(txbname));

    if (txb != null)
    {
        txb.Enabled = p;
        txb.BackColor = p ? HTMLHexToColor("#FFCC99") : Color.LightGray;
    }
}

One Comment

  1. [...] color: #fff; } #ctabs ul.nav { } Aaron BoundyHomeAboutCodeC#Network Ping a Server / Host using C#Converting a Hexadecimal Color to a System.Drawing.Color ObjectSend an Email with System.Net.Mail.MailMessageC# Convert a String to a GuidC# Get the Next Available [...]

Leave a Reply