1

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?

1 Answers1

2

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;
    }
}
Junaith
  • 3,298
  • 24
  • 34
  • Thank you for your help. I moved the code to RowsAdded event. It is OK now. – Jamsheer Moideen Feb 24 '15 at 07:28
  • The flickering problem is solved by moving the code to RowsAdded event. But when the number of records is more ( Say 200 records), it takes 2 to 3 seconds for the grid to load. with CellFormating event, it was loading quickly. – Jamsheer Moideen Feb 24 '15 at 08:37
  • @user1542352 Are you looping the `DataGridView.Rows` to set the image in the RowsAdded event? – Junaith Feb 25 '15 at 02:00
  • Yes. for (int i = e.RowIndex; i < e.RowIndex + e.RowCount; i++) {//Check condition and set image} – Jamsheer Moideen Feb 26 '15 at 05:25