2

I write a string that by format RGB and i want use this string for forcolor textbox? I cut this string to 4 string that values are like(ff,00,12,ff) in visual studio this code run but show error that

values not current format

textbox.ForeColor=
               Color.FromArgb(Convert.ToInt32(a[0]),
                              Convert.ToInt32(a[1]),
                              Convert.ToInt32(a[2]),
                              Convert.ToInt32(a[3]));

please help me about this.

Liam
  • 27,717
  • 28
  • 128
  • 190
user2949651
  • 45
  • 1
  • 1
  • 4

3 Answers3

2

Specify base 16, like this:

Color.FromArgb(Convert.ToInt32(a[0], 16),
               Convert.ToInt32(a[1], 16),
               Convert.ToInt32(a[2], 16),
               Convert.ToInt32(a[3], 16));

ff is not a valid number is base 10. Convert.ToInt32 uses base 10 by default. I assume you have correct values in a array.

For example:

string[] a = {"ff", "00", "12", "ff"};

Color color = Color.FromArgb(Convert.ToInt32(a[0], 16),
                             Convert.ToInt32(a[1], 16),
                             Convert.ToInt32(a[2], 16),
                             Convert.ToInt32(a[3], 16));

Console.WriteLine(color); //prints: Color [A=255, R=0, G=18, B=255]

a more simple way is to use an instance of ColorConverter:

string colorHex = "#" + string.Join("", a);
var color = (Color)new ColorConverter().ConvertFromString(colorHex);
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
1

Your values are in hexademical, so before passing them to FromArgb that accepts only integers, you need to convert them to integers.

int colorR = int.Parse(hexValueOfRed, System.Globalization.NumberStyles.HexNumber);
....
Tigran
  • 61,654
  • 8
  • 86
  • 123
0

I suggest to take a look to the ColorConverter class you can provide directly an argb string to it.

this can be useful: Another question about this

Community
  • 1
  • 1