Reputation: 45
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.
Upvotes: 2
Views: 105
Reputation: 23646
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);
Upvotes: 2
Reputation: 606
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
Upvotes: 0
Reputation: 62265
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);
....
Upvotes: 1