Search code examples
c#datagridviewdatagridviewimagecolumn

DataGridViewImageColumn, images flickering


I have a DataGridView bound to a DataTable on my Windows Form. I want to insert an unbound DataGridViewImagecolumn to it and set the images according to the value of another column. Image is set in DataGidView_CellFormating event. 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?


Solution

  • The flickering is happening because you are setting the image in CellFormatting event handler.

    As per MSDN,the CellFormatting event occurs every time each cell is painted, so you should avoid lengthy processing when handling this event.

    You could set the image by handling DataBindingComplete or CellValueChanged events according to your need.

    You could also enable DoubleBuffering for the DataGridView by creating a custom DataGridView or through reflection for the instance you are using.

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