早上好
我想在 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/