简体   繁体   English

DataGridViewImageColumn,图像闪烁

[英]DataGridViewImageColumn, images flickering

I have a DataGridView bound to a DataTable on my Windows Form. 我在Windows窗体上有一个绑定到DataTable的DataGridView。 I want to insert an unbound DataGridViewImagecolumn to it and set the images according to the value of another column. 我想向其插入未绑定的DataGridViewImagecolumn并根据另一列的值设置图像。 Image is set in DataGidView_CellFormating event. 在DataGidView_CellFormating事件中设置了图像。 Code is as follows 代码如下

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

Everything is working fine. 一切正常。 My problem is that the images shown in cells are flickering. 我的问题是单元格中显示的图像闪烁。 Anybody know why? 有人知道为什么吗?

The flickering is happening because you are setting the image in CellFormatting event handler. 因为您正在CellFormatting事件处理程序中设置图像, CellFormatting发生了闪烁。

As per MSDN ,the CellFormatting event occurs every time each cell is painted, so you should avoid lengthy processing when handling this event. 根据MSDNCellFormatting事件在每次绘制每个单元格时都会发生,因此在处理此事件时应避免进行冗长的处理。

You could set the image by handling DataBindingComplete or CellValueChanged events according to your need. 您可以根据需要通过处理DataBindingCompleteCellValueChanged事件来设置图像。

You could also enable DoubleBuffering for the DataGridView by creating a custom DataGridView or through reflection for the instance you are using. 您还可以通过创建自定义DataGridView或通过反射使用的实例来为DataGridView启用DoubleBuffering

class CustomDataGridView : DataGridView
{
    public CustomDataGridView()
    {
        DoubleBuffered = true;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM