C # - DataGridView - Image and text on the same line


I am looking for something like this on DataGridView:

Image  | Text |
Text   | Text |
Image  | Text

Basically, I just want Image cells and Text cells on the same row. I was able to get it to work with different types, for example: Checkbox, Text, and etc... But I am not able to get it to work with images.

I get this error: Invalid Cast from 'System.String' to 'System.Drawing.Image'

Does anybody know the solution or have suggestion on how I should do this ? Thanks

It is relatively easy to have a column of type DataGridViewImageColumn display text in certain cells.

All you need to do is replace a desired cell with a DataGridViewTextBoxCell.

So for example, if I add the following image column to my grid:

DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn .Name = "ImageColumn";
imageColumn .HeaderText = "An Image!";
Image i = Image.FromFile(@"C:\Pictures\TestPicture.jpg");
imageColumn.Image = i;

You can replace a given cell with text like so (here in a button handler but you could also do it somewhere like within a databinding complete handler).

private void button1_Click(object sender, EventArgs e)
    dataGridView1.Rows[3].Cells["ImageColumn"] = new DataGridViewTextBoxCell();
    dataGridView1.Rows[3].Cells["ImageColumn"].Value = "Some text!";

This solution leaves a little bit of work for you if you want different images (you need to bind to a property of type image) and if you want different text. Since the Value property of an image column is of type Image you cannot use the same binding.

You could make your own overridden image column that handled this, but it would be a bit of work, that might not pay for itself vs. simply setting the value for the cells where you want text directly.