Saturday, July 08, 2006

DataGridViewImageColumn

The first problem I haad with this column type is that my image wasn't showing up - I could see the image just fine in the column editor in Design View, but when I ran my app, only a blank image (red x) showed up.

The problem turned out to be with the DataTable I was binding to. Although the DataTable did have columns corresponding to my two image columns, those columns didn't have any data. Populating them with blank strings in every row fixed the problem...

...and uncovered a bigger problem. Now I was getting a whole slew of these exceptions whenever my DataGridView was first painted:
Invalid cast from System.String to System.Drawing.Image

The problem turned out to be with the names of the DataColumns in my DataTable - the two columns corresponding to my Image Columns were called "Up" and "Down" - e.g.:


this.myDataTable.Columns.AddRange(
new DataColumn[]{
new DataColumn("Description", typeof(string)),
new DataColumn("Up", typeof(string)),
new DataColumn("Down", typeof(string)),
new DataColumn("Delete", typeof(string))});

I'm still not sure why "Up" and "Down" caused a problem - these names happened to be the same as the DataPropertyName for the corresponding DataGridViewImageColumns, so that may have been the problem. Changing these two column names to blank strings or to "1" and "2" solved the problem.

..But now I had a new problem..it seems that when you add a DataGridViewImageColumn, another blank column is automatically added next to the DataGridView. So in this case I was getting two extra columns showing up. The only way I've found around this so far is to figure out the indexes of the extra columns and set their visible property to false.

After all that, I had a nice data grid with my image columns showing up and without any exceptions or extra columns!

1 comment:

CreaTek Solutions said...

Another Quirk -
No matter what order you add your image column into the DataGridView, it will always have the index 0 (if you have more than 1 image column then 0, 1, etc.).

The "extra" column will have the index you would expect your image column to have.

This is true if you add your column from the designer or using Columns.AddRange - I haven't tried it using Columns.Insert