# Friday, October 21, 2011

Custom color in reports : convert color to Hex

I was implementing a client report (RDLC) using the Microsoft Report Viewer control and I wanted to set the background color of a table field based on value from my object source. At first I used the Color.ToKnownColor() method, but discovered that this does not work for all colors. I needed to convert to Hex. Here is the little extension method I used:

public static class ColorExtensions
{
 
    #region -- Data Members --
    static char[] hexDigits = {
     '0', '1', '2', '3', '4', '5', '6', '7',
     '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    #endregion
 
 
    /// <summary>
    /// Convert a .NET Color to a hex string.
    /// </summary>
    /// <returns>ex: "#FFFFFF", "#554ECE"</returns>
    public static string ToHexString( this Color color )
    {
        byte[] bytes = new byte[3];
        bytes[0] = color.R;
        bytes[1] = color.G;
        bytes[2] = color.B;
        char[] chars = new char[bytes.Length * 2];
        for ( int i = 0; i < bytes.Length; i++ )
        {
            int b = bytes[i];
            chars[i * 2] = hexDigits[b >> 4];
            chars[i * 2 + 1] = hexDigits[b & 0xF];
        }
        return "#" + new string( chars );
    }
 
}
#    Comments [3] |
Wednesday, December 07, 2011 3:06:59 AM (Eastern Standard Time, UTC-05:00)
Your article was exclelnet and erudite.
Thursday, December 08, 2011 9:18:38 AM (Eastern Standard Time, UTC-05:00)
YYJupx , [url=http://ocnlzogtwexq.com/]ocnlzogtwexq[/url], [link=http://csnykfrlgenn.com/]csnykfrlgenn[/link], http://xtjumxycxdsr.com/
Sunday, December 11, 2011 1:53:28 PM (Eastern Standard Time, UTC-05:00)
vLqMrd , [url=http://dhnbwejcnflv.com/]dhnbwejcnflv[/url], [link=http://dflenymnbquz.com/]dflenymnbquz[/link], http://jlxbnzykqmiw.com/
Comments are closed.