Reputation: 12309
I want to set the backcolor of a web form programmatically at run time (so the user can select his or her preferred color).
I can do this with a named color, as in:
txt1.BackColor = System.Drawing.Color.PeachPuff;
but I am having a hard time figuring out how to set the color using the RGB value, as in:
txt1.BackColor = SomeConverter("#FEC200");
How is this done?
Upvotes: 2
Views: 2950
Reputation: 12309
There was another answer by @Hossein-Narimani-Rad that he deleted that said to use ColorConverter.ConvertFromString. I tried it and got it to work like this:
System.Drawing.ColorConverter conv = new System.Drawing.ColorConverter();
txt1.BackColor = (System.Drawing.Color)conv.ConvertFromString("#FEC200");
But @Win 's and @Manish-Mishra 's answers are more concise and what I am going with.
Upvotes: 0
Reputation: 12375
use this
txt1.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEC200");
also, if you want to convert the System.Drawing.Color
back to string(to save in db), do this:
private static String ConvertToHex(System.Drawing.Color color)
{
return "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
}
private static String ConvertToRGB(System.Drawing.Color color)
{
return "RGB(" + color.R.ToString() + "," + color.G.ToString() + "," + color.B.ToString() + ")";
}
Upvotes: 3