0

I have this code:

        int converted = Convert.ToInt32(value);
        string hexValue = converted.ToString("X");
        Color color = System.Drawing.ColorTranslator.FromHtml("#" + hexValue);
        return color;

That get strings like "12222222" and converts them to C# colors. But I'm getting this string "255" and I don't know how to handle this. Can anyone shed some light on this strange number?

Thanks

Update Forgot to mention: in a demo project his function works with value="255". In my project - doenst.

Ehud Grand
  • 3,501
  • 4
  • 33
  • 52

3 Answers3

0

try

string hexValue = converted.ToString("X8");

that will ensure that there are 8 characters in the hexValue

MikeW
  • 1,568
  • 2
  • 19
  • 39
0

If you want to convert an integer (int or Int32) to a Color you can simply use:

 // value is an integer in this case
 Color color = Color.FromArgb(value);

No need to convert it to a hex string.

If you want to convert a decimal String to a Color just use:

 int value = Int32.Parse(decimalString);
 Color color = Color.FromArgb(value);

if you want to convert a hexadecimal String to a Color:

 int value = Int32.Parse(hexString, NumberStyles.HexNumber); // System.Globalization
 Color color = Color.FromArgb(value);
MrPaulch
  • 1,423
  • 17
  • 21
  • Color.FromArgb does not accept a string as a parameter, which it appears from the question that value is – MikeW Jul 10 '14 at 09:27
  • Well updated answer to cover all bases... though the op still did not clarify what his `value` variable is – MrPaulch Jul 10 '14 at 09:30
0

There is a converter in the framework.

From this question:

System.Windows.Media.ColorConverter

var color = (Color)ColorConverter.ConvertFromString("#FF010203");
Community
  • 1
  • 1
Emond
  • 50,210
  • 11
  • 84
  • 115