Reputation: 680
Im Trying to add a Image column From My Project's Resources to a newly created DataGridView This Is the Code:
DataGridViewImageColumn myImage = new DataGridViewImageColumn();
myImage.Image = Properties.Resources.bullet_arrow_down;
myImage.ImageLayout = DataGridViewImageCellLayout.Zoom;
myImage.Name = "Remove";
DirectoryGrid.Columns.Add(myImage);
But When i run the code i get the default "X" Image and not my selected image. Is the Image Over Sized?(it's a 32x32 ico) Must i add some bit conversion to it?
Most Code Online Wants you to load a image from a file,but i think that is messy.But if i have to so be it.But i found some references to indicate that this code should work fine.
Please note this image is used in another button and its working fine. And i have tried other images as well.
Upvotes: 3
Views: 3350
Reputation: 5454
What you have will work for rows that are added via DataGridView.DataSource
. However, as you've seen, the NewRow
still displays a red x
. This could be solved as shown here. However, once you've edited a cell of the NewRow
and another one is added, the editing row no longer has your image, but is back to the red x
.
Solution
Instead of handling the CellFormatting
event, handle DataGridView.RowsAdded
:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
if (this.dataGridView1.Columns.Contains("ImageColumnName"))
{
this.dataGridView1.Rows[e.RowIndex].Cells["ImageColumnName"].Value = Properties.Resources.MySavedImage;
}
}
However, this won't catch the very first NewRow
added because it is added once the first column is added to the DataGridView
. So unless that first column is your image column, you'll also need to do the following:
this.dataGridView1.Columns.Add(myImageColumn);
this.dataGridView1.Rows[this.dataGridView1.NewRowIndex].Cells["ImageColumnName"].Value = Properties.Resources.MySavedImage;
Upvotes: 2