Reputation: 11090
I have a DataGridView
with an image column. In the properties, I am trying to set the image. I click on image, choose the project resource file, and then select one of the images displayed. However, the image still shows as a red x on the DataGridView? Anybody know why?
Upvotes: 15
Views: 64807
Reputation: 38865
While functional, there is a pretty significant issue with the answer presented. It suggests loading images directly from Resources
:
dgv2.Rows[e.RowIndex].Cells[8].Value = Properties.Resources.OnTime;
The problem is that this creates a new image object each time as can be seen in the resource designer file:
internal static System.Drawing.Bitmap bullet_orange {
get {
object obj = ResourceManager.GetObject("bullet_orange", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
If there are 300 (or 3000) rows with that same status, each does not need its own image object, nor does it need a new one each time the event fires. Secondly, previously created images are not being disposed.
To avoid all this, just load resource images into an array and use/assign from there:
private Image[] StatusImgs;
...
StatusImgs = new Image[] { Resources.yes16w, Resources.no16w };
Then in the CellFormatting
event:
if (dgv2.Rows[e.RowIndex].IsNewRow) return;
if (e.ColumnIndex != 8) return;
if ((bool)dgv2.Rows[e.RowIndex].Cells["Active"].Value)
dgv2.Rows[e.RowIndex].Cells["Status"].Value = StatusImgs[0];
else
dgv2.Rows[e.RowIndex].Cells["Status"].Value = StatusImgs[1];
The same 2 image objects are used for all the rows.
Upvotes: 5
Reputation: 17691
For example you have DataGridView control named 'dataGridView1' with two text columns and one image column. You have also an images in resource file named 'image00' and 'image01'.
You can add images while adding rows like this:
dataGridView1.Rows.Add("test", "test1", Properties.Resources.image00);
You can also change image while your app is running:
dataGridView1.Rows[0].Cells[2].Value = Properties.Resources.image01;
or you can do like this ...
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name == "StatusImage")
{
// Your code would go here - below is just the code I used to test
e.Value = Image.FromFile(@"C:\Pictures\TestImage.jpg");
}
}
Upvotes: 33