2015-02-24 152 views
0

我有一個DataGridView綁定到我的Windows窗體上的DataTable。我想插入一個未綁定的DataGridViewImagecolumn,並根據另一列的值設置圖像。圖像在DataGidView_CellFormating事件中設置。代碼如下DataGridViewImageColumn,圖像閃爍

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

一切工作正常。我的問題是單元格中顯示的圖像閃爍。任何人都知道爲什麼?

+0

閃爍?你可以發佈視頻/ gif嗎?你的意思是iPhone的效果(當你拿着一個隨機圖標時) – Ave 2015-02-24 06:04:47

+0

不像iPhone的圖標閃爍。但感覺就像每秒刷新一次。我不知道如何發佈視頻。 – 2015-02-24 06:22:04

+0

哦,我明白了。不確定這個問題。 – Ave 2015-02-24 06:28:36

回答

1

閃爍正在發生,因爲您正在設置CellFormatting事件處理程序中的圖像。

根據MSDNCellFormatting事件發生在每次繪製每個單元格時,因此在處理此事件時應避免冗長的處理。

根據您的需要,您可以通過處理DataBindingCompleteCellValueChanged事件來設置圖像。

您還可以通過創建自定義DataGridView或通過反射您正在使用的實例來爲DataGridView啓用DoubleBuffering

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

謝謝你的幫助。我將代碼移到了RowsAdded事件中。現在可以。 – 2015-02-24 07:28:55

+0

通過將代碼移動到RowsAdded事件來解決閃爍的問題。但是當記錄數量更多時(說200條記錄),網格加載需要2到3秒。與CellFormating事件,它很快加載。 – 2015-02-24 08:37:55

+0

@ user1542352你循環DataGridView.Rows來設置RowsAdded事件中的圖像嗎? – Junaith 2015-02-25 02:00:49