c# - DataGridView 中的图像问题

标签 c# .net winforms image datagridview

早上好

我想在 DataGridView 中显示图像(16*16px png 文件)。此网格有 3 列:文本单元格、文本单元格、图像单元格。 这是示例,我如何尝试设置图像:

    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.Check;
            }
            else
            {
                cell.Value = (System.Drawing.Image)Properties.Resources.Cancel;
            }
        }
    }

但在网格中,我只在纸上显示红叉,如未找到文件错误。 你能帮帮我吗?

最佳答案

如果您将分配图像的逻辑放在 DataGridView 的 CellFormatting 事件中,这应该有效:

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

另请注意,您在此处设置的是 e.Value 而不是 cell.Value。

关于c# - DataGridView 中的图像问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6892609/

相关文章:

.net - ListView 的 DragEnter、DragOver、DragDrop 事件未引发 (AllowDrop=True)

c# - 将 Microsoft.AspNet.Identity.EntityFramework.3.0.0-rc1-final 安装到类库中

c# - 序列化继承 : Will an exception be thrown if the base class isn't marked [Serializable]?

c# - DbSet 不包含 FirstOrDefault 的定义?

c# - .Net 程序集加载问题期间出现 BadImageFormatException

C# 应用程序需要在 Citrix 环境中引用远程工作站

c# - var 关键字与实际类型?

c# - 如何散列密码

c# - 返回类型比方法更难访问

c# - ListView 项目不移动