Image showing red "X" in DataGridView when loaded from resources

Im. Trying to add an image column from the My Project Resources list 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, not my selected image. Is the image stronger? (It's 32x32 ico) Should I add some conversion to it?

Most Code Online Want you to download an image from a file, but I think it's a mess. But if I should be. But I found some links to point out that this code should work fine.

Please note that this image is used in another button and works fine. And I have tried other images as well.

+3


source to share


1 answer


What you have will work for lines that are added through DataGridView.DataSource

. However, as you saw, it NewRow

still displays red x

. This can be solved as shown here . However, once you've edited a cell NewRow

and added another one, the edit line no longer has your image, but will revert to red x

.

Decision

Instead of handling the event CellFormatting

, the handle is 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 will not catch the first added NewRow

one because it is added after the first column is added to DataGridView

. Therefore, if that first column is not your image column, you will need to do the following as well:

this.dataGridView1.Columns.Add(myImageColumn);
this.dataGridView1.Rows[this.dataGridView1.NewRowIndex].Cells["ImageColumnName"].Value = Properties.Resources.MySavedImage;

      

+2


source







All Articles