如果存在另一列中指定的路径,我需要更改列的图像。
我有以下代码:
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;
它会显示但在条件不会改变。
此外,是否有更好的方法将图像添加到datagridview单元格。
感谢任何帮助。感谢
答案 0 :(得分:6)
您可以将代码放在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而不是cell.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");
}
}
}
}
在示例中,我有一个包含整数值的列,但它应该以类似的方式用于文本。