Image Displaying a Red “X” in a DataGridView when loading from Resources

只谈情不闲聊 提交于 2020-01-04 00:40:25

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/30802160/image-displaying-a-red-x-in-a-datagridview-when-loading-from-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!