c# - How to convert a hex string to color

Convert a Hex String to a Color
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can convert a Hex String object to a Color. The Color represents an ARGB (alpha, red, green, blue) color.

The ColorTranslator class translates color to and from GDI+ Color structures. The ColorTranslator class cannot be inherited. The ColorTranslator FromHtml(String) method translates an HTML color representation to a GDI+ Color structure. The ColorTranslator FromHtml(string htmlColor) method’s htmlColor parameter is a String representation of the HTML color to translate.

ColorTranslator FromHtml(string htmlColor) method returns the Color structure that represents the translated HTML color or Empty if the htmlColor color is null. So, using this ColorTranslator FromHtml() method .net c# developers can convert a Hex String instance to a Color object.

<%@ Page Language="C#" AutoEventWireup="true"%>
<%@ Import Namespace="System.Drawing" %>
<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)  
        //this section create string variables.  
        string hexString = "#FF0000";
        string hexString2 = "#F5DEB3";

        Label1.Text = "hexadecimal color string..................<br />";
        Label1.Text += hexString;

        Label1.Text += "<br /><br />hexadecimal color code2..................<br />";
        Label1.Text += hexString2;

        //this line create a red color from hexadecimal color string.
        Color c = ColorTranslator.FromHtml(hexString);

        //this line create a wheat color from hexadecimal color code.
        Color c2 = ColorTranslator.FromHtml(hexString2);

        //applying text color to label control
        Label1.ForeColor = c;
        //applying background color to label control.
        Label1.BackColor = c2;
        //applying new font size of label.
        Label1.Font.Size = FontUnit.XXLarge;
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - color from hex string</title>    
    <form id="form1" runat="server">    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - color from hex string
        <hr width="550" align="left" color="Gainsboro" />    
        <br /><br />  
            Text="color from hex string"    
More c# examples