无法更改datagridview winforms中的图像
本文关键字:图像 winforms datagridview | 更新日期: 2023-09-27 18:00:14
如果在另一列中存在指定的路径,我需要更改列的图像。
我有以下代码:
dataGridView1.DataSource = table;
DataGridViewButtonColumn buttonCol = new DataGridViewButtonColumn();
buttonCol.HeaderText = "";
buttonCol.Name = "BrowseButton";
buttonCol.Text = "...";
buttonCol.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(buttonCol);
DataGridViewImageColumn imgCol = new DataGridViewImageColumn();
imgCol.HeaderText = "Status";
imgCol.Name = "StatusImage";
imgCol.Image = null;
dataGridView1.Columns.Add(imgCol);
dataGridView1.Columns["StatusImage"].DisplayIndex = 4;
foreach (DataGridViewRow myRow in dataGridView1.Rows)
{
string overRiddenDirPath = myRow.Cells["Overridden Dir"].Value.ToString();
string preConfiguredPath = myRow.Cells["PreConfigured Dir"].Value.ToString();
string path = overRiddenDirPath;
if (overRiddenDirPath == "")
{
path = preConfiguredPath;
}
DataGridViewImageCell cell = myRow.Cells["StatusImage"] as DataGridViewImageCell;
// If the directory doesn't exist
if (!Directory.Exists(path))
{
cell.Value = Image.FromFile(@"Chrysanthemum.jpg");
}
else
{
cell.Value = Image.FromFile(@"Jellyfish.jpg");
}
}
没有显示任何图像:图像的路径很好,因为如果我这样说:
DataGridViewImageColumn imgCol = new DataGridViewImageColumn();
imgCol.HeaderText = "Status";
imgCol.Name = "StatusImage";
imgCol.Image = Image.FromFile(@"Chrysanthemum.jpg");
dataGridView1.Columns.Add(imgCol);
dataGridView1.Columns["StatusImage"].DisplayIndex = 4;
它会被显示,但不会随条件而改变。
此外,是否有更好的方法将图像添加到数据网格视图单元格中。
感谢您的帮助。感谢
您可以将代码放在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,而不是单元格。此处显示值。
以下是我尝试的一个示例中的代码,在该示例中,我访问另一列的值以有条件地更改所选图像。无论图像具有哪个显示索引,这都能完美工作。
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (!dataGridView1.Rows[e.RowIndex].IsNewRow)
{
if (dataGridView1.Columns[e.ColumnIndex].Name == "StatusImage")
{
if (((int)dataGridView1.Rows[e.RowIndex].Cells["ValueTwo"].Value) == 5)
{
e.Value = Image.FromFile(@"C:'Pictures'TestImage1.jpg");
}
else
{
e.Value = Image.FromFile(@"C:'Pictures'TestImage2.jpg");
}
}
}
}
在这个例子中,我有一个包含整数值的列,但它应该以类似的方式适用于文本。