3

I am passing a hex value in my QueryString. I'd like to convert that to a color to use the ForeColor in a cell in a grid view. Tried both System.Drawing.ColorTranslator.FromHtml() and System.Drawing.Color.FromArgb() with no luck.

My QueryString is urlencoded so the part that matters looks like:

QueryString...&color=%23AA4643

Below is how I have tried .FromArg:

string sColor = Request.QueryString["color"]; // sColor is now #AA4643
Int32 iColorInt = Convert.ToInt32(sColor,16); //Get error message - Could not find any recognizable digits
Color curveColor = System.Drawing.Color.FromArgb(iColorInt); //Never makes it here

And here is how I have tried .FromHtml:

string sColor = Request.QueryString["color"]; 
System.Drawing.Color myColor = new System.Drawing.Color();
myColor = System.Drawing.ColorTranslator.FromHtml(sColor);

In this case myColor gets set to - myColor = "{Name=ffaa4643, ARGB=(255, 170, 70, 67)}"

But when I go to use it I get an error:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Any and all help greatly appreciated

1 Answer 1

8

Try this:

string sColor = Request.QueryString["color"]; // sColor is now #AA4643
Int32 iColorInt = Convert.ToInt32(sColor.Substring(1),16); 
Color curveColor = System.Drawing.Color.FromArgb(iColorInt); 
Sign up to request clarification or add additional context in comments.

3 Comments

Thaks, that gets past the line it was erroring on and sets curveColor to: curveColor = "{Name=aa4643, ARGB=(0, 170, 70, 67)}" But when I go to use it in the grid I get same error as other attempt "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"
It means that sometimes you have Request.QueryString["color"] as empty. Please check it under debugger
SergeyS your solution does in fact work as does my other one. I was so focused on the color I was not looking at where I was setting it. I needed my line to set the color AFTER I called grid.DataBind. There was no Rows in my grid yet...Was so focused on the conversion of the color I overlooked the obvious Thanks! BTW this also works:System.Drawing.ColorConverter oConverter = new System.Drawing.ColorConverter(); Color myColor = (Color)oConverter.ConvertFromString(sColor);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.