A small application I’m working on at the moment needs to present the user some colours and the ability to change them and save changes. So, I decided to use a DataGridView with a custom colour picker column (that’s a separate story I think). The colours are stored in the database table as integers in ARGB format. So, to present them, I need to convert them to System.Drawing.Color.
I have a piece of code like that
public DataTable GetColours()
{
// snip
DataTable colors = new DataTable();
// snip
colors.Columns.Add(MyColourTypes.BackGroundColour.ToString());
// snip
DataRow newRow = colors.NewRow();
int bgColour;
if (int.TryParse(iMyColourValue.ToString(), out bgColor))
{
newRow[MyColourTypes.BackGroundColour.ToString()] = Color.FromArgb(bgColor);
}
else
{
newRow[MyColourTypes.BackGroundColour.ToString()] = Color.Empty;
}
}
So if a value in the database is int, I convert it to Color and add to DataTable, otherwise I put Color.Empty in the DataTable (Colours can be nulls).
However, my DataGridView complained about the invalid cast exception on the line
Color lclcolor = (Color)value;
Where value is the entry from my DataTable.
So I thought that the colours in the database may be not “known colours” and spent at least an hour searching for a “proper” way to convert a colour from integer to System.Drawing.Color. It took a while till I noticed in the watch window that even when the value is “Color[Black]” the debugger refuses to unbox it as a System.Drawing.Color. Further investigation proved, that value is indeed not a Color structure, but more looks like a string. Another minute of intense thinking, and I replace
colors.Columns.Add(MyColourTypes.BackGroundColour.ToString());
with
colors.Columns.Add(MyColourTypes.BackGroundColour.ToString(), typeof(Color));
A rainbow of colours appear in my DataGridView.
Moral: when you want to store something more complex than a string or an int in a DataTable, don’t forget to tell the table what type of object you want to store.
Good thing: I learned a few things about converting colours between different format
No comments:
Post a Comment