Search code examples
c#visual-studio-2010datagridviewdatagridcolumn

DataGridViewImageColumn don't display the value - why?


I want to display some images in my dataGridView, so I created DataGridViewImageColumn with default image (Properties.Resources.test), added it to dataGridView and tried to insert some values to cells. Unfortunately it didn't change the display. What Am I doing wrong?

        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++;
        }

Solution

  • As explained in the question in the comment you need to use the CellFormatting event like so:

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

    So set e.Value rather than cell.Value and assign the image.