DataGridViewImageColumn不显示值 - 为什么?

时间:2011-10-25 14:15:09

标签: c# visual-studio-2010 datagridview datagridcolumn

我想在我的dataGridView中显示一些图像,因此我使用默认图像(DataGridViewImageColumn)创建了Properties.Resources.test,将其添加到dataGridView并尝试向单元格插入一些值。不幸的是它没有改变显示。我做错了什么?

        var q = from a in _dc.GetTable<Map>() select a;
        View.dataGridView1.DataSource = q;
        View.dataGridView1.Columns[3].Visible = false;

        var imageColumn = new DataGridViewImageColumn
        {
            Image = Properties.Resources.test,
            ImageLayout = DataGridViewImageCellLayout.Stretch,
            Name = "Map",
            HeaderText = @"map"
        };
        View.dataGridView1.Columns.Add(imageColumn);

        var i = 0;
        foreach (var map in q)
        {
            View.dataGridView1.Rows[i].Cells[8].Value = ByteArrayToImage(map.map1.ToArray());
            i++;
        }

2 个答案:

答案 0 :(得分:1)

正如评论中的问题所解释的那样,您需要使用CellFormatting事件,如下所示:

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

因此设置e.Value而不是cell.Value并分配图像。

答案 1 :(得分:0)

你可以这样做......

 for(int i = 0; i < dataGridView1.Columns.Count; i ++)
            if(dataGridView1.Columns[i] is DataGridViewImageColumn) {
                ((DataGridViewImageColumn)dataGridView1.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
                break;
            }