Datagridview图像列设置图像 – C#

我有一个带有图像列的DataGridView 。 在属性中,我试图设置图像。 我单击图像,选择项目资源文件,然后选择显示的图像之一。 但是,图像仍显示为DataGridView上的红色x? 谁知道为什么?

例如,您有名为“dataGridView1”的DataGridView控件,其中包含两个文本列和一个图像列。 您还在资源文件中有一个名为“image00”和“image01”的图像。

您可以在添加如下行的同时添加图像:

  dataGridView1.Rows.Add("test", "test1", Properties.Resources.image00); 

您还可以在应用运行时更改图像:

  dataGridView1.Rows[0].Cells[2].Value = Properties.Resources.image01; 

或者你可以这样做……

 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"); } } 

虽然function正常,但提出的答案存在一个非常重要的问题。 它建议直接从Resources加载图像:

 dgv2.Rows[e.RowIndex].Cells[8].Value = Properties.Resources.OnTime; 

问题是每次都会创建一个新的图像对象,如资源设计器文件中所示:

 internal static System.Drawing.Bitmap bullet_orange { get { object obj = ResourceManager.GetObject("bullet_orange", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } 

如果有300(或3000)行具有相同的状态,则每个行都不需要自己的图像对象,每次事件触发时也不需要新的图像对象。 其次,先前创建的图像未被处理。

要避免这一切,只需将资源图像加载到数组中并使用/ assign:

 private Image[] StatusImgs; ... StatusImgs = new Image[] { Resources.yes16w, Resources.no16w }; 

然后在CellFormatting事件中:

 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]; 

所有行都使用相同的2个图像对象。