开发者

Problem with Image in DataGridView

Good morning,

I want to show image (16*16px png file) in DataGridView. This Grid has 3 columns: text cell, text cell, image cell. Here is sample, how I try set image:

    private void showData(List<Item> collection)
    {
        gwQuestions.AutoGenerateColumns = false;
        gwQuestions.DataSource = addNotSet(collection);

        foreach (DataGridViewRow row in gwQuestions.Rows)
        {
            DataGridViewImageCell cell = row.Cells[2] as DataGridViewImageCell;
            cell.ValueType = typeof(System.Drawing.Image);
            if (collection[row.Index].Result)
            {
                cell.Value = (System.Drawing.Image)Properties.Resources.Ch开发者_运维百科eck;
            }
            else
            {
                cell.Value = (System.Drawing.Image)Properties.Resources.Cancel;
            }
        }
    }

But in grid i show only red cross on paper, like File not found error. Can you help me please?


This should work if you put your logic to assign the image within the CellFormatting event of the DataGridView:

dataGridView1.CellFormatting += dataGridView1_CellFormatting;

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{            
    if (dataGridView1.Columns[e.ColumnIndex].Name == "ImageColumnName")
    {
        if (collection[e.RowIndex].Result)
        {
            e.Value = (System.Drawing.Image)Properties.Resources.Check;
        }
        else
        {
            e.Value = (System.Drawing.Image)Properties.Resources.Cancel;
        }
    }
}

Also note that you set e.Value rather than cell.Value here.


Salvete! I was looking for a similar answer. If you don't mind my vb, try this post (where I answered myself...). The code shows how to load an image from resource into a datagridview.

How to dynamically swap a string for an image in Datagridview?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜