Dar*_*ung 13 c# datagridview winforms
我有一个DataGridView
图像列.在属性中,我试图设置图像.我单击图像,选择项目资源文件,然后选择其中一个显示的图像.但是,图像仍然在DataGridView上显示为红色x?谁知道为什么?
Eni*_*ate 28
例如,您有名为"dataGridView1"的DataGridView控件,其中包含两个文本列和一个图像列.您还在资源文件中有一个名为"image00"和"image01"的图像.
您可以在添加如下行时添加图像:
dataGridView1.Rows.Add("test", "test1", Properties.Resources.image00);
Run Code Online (Sandbox Code Playgroud)
您还可以在应用运行时更改图像:
dataGridView1.Rows[0].Cells[2].Value = Properties.Resources.image01;
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做......
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");
}
}
Run Code Online (Sandbox Code Playgroud)
虽然功能正常,但所提供的答案存在一个相当重要的问题。它建议直接从以下位置加载图像Resources
:
dgv2.Rows[e.RowIndex].Cells[8].Value = Properties.Resources.OnTime;
Run Code Online (Sandbox Code Playgroud)
问题是,这每次都会创建一个新的图像对象,如资源设计器文件中所示:
internal static System.Drawing.Bitmap bullet_orange {
get {
object obj = ResourceManager.GetObject("bullet_orange", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
Run Code Online (Sandbox Code Playgroud)
如果有 300(或 3000)行具有相同的状态,则每一行不需要自己的图像对象,也不需要每次事件触发时都需要一个新的图像对象。其次,以前创建的图像不会被处理。
为了避免这一切,只需将资源图像加载到数组中并从那里使用/分配:
private Image[] StatusImgs;
...
StatusImgs = new Image[] { Resources.yes16w, Resources.no16w };
Run Code Online (Sandbox Code Playgroud)
那么在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];
Run Code Online (Sandbox Code Playgroud)
所有行都使用相同的 2 个图像对象。