Casey Crookston
Casey Crookston

Reputation: 13965

Convert System.Drawing.Color to an int?

In the database, we have colors being stored as int's. (Don't ask... it's a really old app.) Example:

-16777216 = black

I am able to convert -16777216 to #000000 (which I can actually use in the UI):

string htmlColor = ConvertToColor("-16777216");

Will return "#000000" from this method:

private string ConvertColor(string value)
{
    int valInt = Convert.ToInt32(value);
    System.Drawing.Color color = System.Drawing.Color.FromArgb(valInt);
    return System.Drawing.ColorTranslator.ToHtml(color);
}

But now, to re-save the value in the same format, I'm having trouble going backwards:

string intColor = RevertColor("#000000");

Here's what I have so far:

private string RevertColor(string value)
{
    System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml(value);
    return ????;
}

Upvotes: 1

Views: 7672

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 416149

If FromArgb() worked going one direction, it seems like ToArgb() should work in the other direction:

private string RevertColor(string value)
{    
    return System.Drawing.ColorTranslator.FromHtml(value).ToArgb().ToString();
}

... but I'm also not sure I appreciate all the nuances in involved. If this doesn't do the job, please explain how it fails.

It also seems very weird that you want a string at all, if they're really int values in the database. That scares me you might be using really unsafe practices with how you save these values in the SQL. If nothing else, it's sub-optimal for performance to convert back and forth between strings like that. Thanks to culture/internationalization issues, those conversion operations are a lot more expensive than you might think.

Upvotes: 4

Related Questions