Click here to Skip to main content
15,896,063 members
Articles / Programming Languages / C#
Tip/Trick

Convert RGB Color to hex

Rate me:
Please Sign up or sign in to vote.
1.80/5 (4 votes)
5 May 2011CPOL 29.2K   1   5
C#
private string HexFromRGB(int r, int g, int b)
        {
            return ColorTranslator.FromHtml(String.Format("#{0:X2}{1:X2}{2:X2}", r, g, b)).Name.Remove(0,2);
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I do not claim to be wrong! I just rarely ever write.

Comments and Discussions

 
GeneralYou are correct Chris, sorry was in the middle of two differ... Pin
charles henington14-May-11 6:27
charles henington14-May-11 6:27 
You are correct Chris, sorry was in the middle of two different projects when posted this tip but still no excuse., the string.Format() method would easily suffice for formatting the rgb to hex. EdMan apoligies for the lack of explanation on the tip/trick, thought the title gave it away, sometimes we forget to remember that the tip/tricks that we supply are also read by newbies to the language and should be adaquately explained. String.Format is a very important tool you will want to read up on this topic. A simple example would be MessageBox.Show(String.Format("Your Name is {0}!!!", textBox1.Text)); if the text in textBox1 is EdMan the output would be.... Your Name Is EdMan!!!
GeneralRe: That sound better :) And yes, I probably ought to read up on... Pin
Ed Nutting15-May-11 4:14
Ed Nutting15-May-11 4:14 
GeneralWouldn't have an answer to what Chris Trelawny-Ross said but... Pin
Ed Nutting7-May-11 23:38
Ed Nutting7-May-11 23:38 
GeneralRe: check out my reply Pin
charles henington15-May-11 4:07
charles henington15-May-11 4:07 
GeneralUmm... the string.Format() method (with the format string yo... Pin
Chris Trelawny-Ross6-May-11 12:04
Chris Trelawny-Ross6-May-11 12:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.