【问题标题】:Datagridview Image Column Setting Image - C#Datagridview 图像列设置图像 - C#
【发布时间】:2012-01-01 04:42:50
【问题描述】:

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

【问题讨论】:

  • 你想从资源文件中加载图片 ....

标签: c# winforms datagridview


【解决方案1】:

例如,您有名为“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"); 
        } 
   } 

【讨论】:

  • @Darren Young 如果这不起作用,请发表评论,我会为此提供更多代码..
  • 警告:资源是一个生成器:此代码为网格的每一行创建一个新图像。它不会重复使用图像
【解决方案2】:

虽然功能正常,但给出的答案存在一个非常重要的问题。建议直接从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)行具有相同的状态,则每行都不需要自己的图像对象,也不需要每次触发事件时都需要新的图像对象。其次,之前创建的图像不会被释放。

为了避免这一切,只需将资源图像加载到数组中并从那里使用/分配:

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 个图像对象用于所有行。

【讨论】:

    猜你喜欢
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    相关资源
    最近更新 更多