C# Datagridview图像列设置图像-C
我有一个带有图像列的DataGridView。在属性中,我尝试设置图像。我单击图像,选择项目资源文件,然后选择一个显示的图像。但是,图像在DataGridView上仍然显示为红色x?有人知道为什么吗?例如,您有一个名为“dataGridView1”的DataGridView控件,它有两个文本列和一个图像列。资源文件中还有一个名为“image00”和“image01”的图像 可以在添加行时添加图像,如下所示:C# Datagridview图像列设置图像-C,c#,winforms,datagridview,C#,Winforms,Datagridview,我有一个带有图像列的DataGridView。在属性中,我尝试设置图像。我单击图像,选择项目资源文件,然后选择一个显示的图像。但是,图像在DataGridView上仍然显示为红色x?有人知道为什么吗?例如,您有一个名为“dataGridView1”的DataGridView控件,它有两个文本列和一个图像列。资源文件中还有一个名为“image00”和“image01”的图像 可以在添加行时添加图像,如下所示: dataGridView1.Rows.Add("test", "test1", Pr
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");
}
}
虽然是功能性的,但给出的答案存在一个相当重要的问题。它建议直接从资源加载图像: 问题在于,这样每次都会创建一个新的图像对象,如资源设计器文件中所示:
internal static System.Drawing.Bitmap bullet_orange {
get {
object obj = ResourceManager.GetObject("bullet_orange", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
如果有300或3000行具有相同的状态,则每个行不需要自己的图像对象,也不需要每次触发事件时都有一个新的图像对象。第二,不处理先前创建的图像
要避免所有这些情况,只需将资源映像加载到阵列中,然后从那里使用/分配:
private Image[] StatusImgs;
...
StatusImgs = new Image[] { Resources.yes16w, Resources.no16w };
然后在CellFormatting事件中:
所有行都使用相同的2个图像对象。您想从资源文件加载图像…@Darren Young如果这不起作用,请留下评论,我将为此提供更多代码。。
private Image[] StatusImgs;
...
StatusImgs = new Image[] { Resources.yes16w, Resources.no16w };
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];