DataGridViewImageColumn,图像闪烁
本文关键字:闪烁 图像 DataGridViewImageColumn | 更新日期: 2024-07-27 14:36:02
我的Windows窗体上有一个绑定到DataTable的DataGridView。我想在其中插入一个未绑定的DataGridViewImagecolumn,并根据另一列的值设置图像。在DataGidView_CellFormating事件中设置图像。代码如下
DataGridView dgvResult = new DataGridView();
dgvResult.DataSource = dtResult;
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn.Width = 40;
imageColumn.Name = "Image";
imageColumn.HeaderText = "";
dgvResult.Columns.Insert(0, imageColumn);
private void dgvResult_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dgvResult.Columns[e.ColumnIndex].Name == "Image")
{
DataGridViewRow row = dgvResult.Rows[e.RowIndex];
if (Utils.isNumeric(row.Cells["CM_IsExport"].Value.ToString()) && Int32.Parse(row.Cells["CM_IsExport"].Value.ToString()) == 1)
{
row.Cells["Image"].Value = Properties.Resources.export16;
}
else { row.Cells["Image"].Value = Properties.Resources.plain16; }
}
}
一切都很好。我的问题是显示在单元格中的图像在闪烁。有人知道为什么吗?
闪烁是因为您正在CellFormatting
事件处理程序中设置图像。
根据MSDN,每次绘制每个单元格时都会发生CellFormatting
事件,因此在处理此事件时应避免处理时间过长。
您可以根据需要通过处理DataBindingComplete
或CellValueChanged
事件来设置图像。
您还可以通过创建自定义DataGridView
或通过反射为正在使用的实例为DataGridView
启用DoubleBuffering
。
class CustomDataGridView : DataGridView
{
public CustomDataGridView()
{
DoubleBuffered = true;
}
}