2011-11-18 80 views
11

我有一个DataGridView与图像列。在属性中,我试图设置图像。我点击图像,选择项目资源文件,然后选择一个显示的图像。但是,该图像仍然显示为DataGridView上的红色x?任何人都知道为什么?Datagridview图像列设置图像 - C#

+0

你想从资源文件加载图像.... –

回答

23

例如,您有包含两个文本列和一个图像列的名为'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"); 
     } 
    } 
+0

@Darren杨,你会留下评论,如果这不工作,我会提供更多的代码.. –

1

虽然功能正常,但所提供的答案存在一个相当重要的问题。这表明加载图像直接从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个图像对象对于所有的行。