2009-12-01 47 views
3

我使用C#,的WinForms和.Net 3.5的DataGridView CellFormatting事件預防形式畫

我的形式有一個自定義DataGridView(雙緩衝,以防止在我cellformatting事件閃爍,as seen here)。當我執行數據庫搜索時,我將結果數據集綁定到datagridview

我處理CellFormatting事件,根據數據爲行繪製某種顏色。

我的DataGridView代碼:

resultsGridView.DataSource = results.DefaultViewManager.DataSet.Tables[0]; 
resultsGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue; 
resultsGridView.BorderStyle = BorderStyle.Fixed3D; 
resultsGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(resultsGridView_CellFormatting); 

我CellFormatting代碼:除了

void resultsGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    int rowIndex = e.RowIndex; 
    DataGridViewRow therow = resultsGridView.Rows[rowIndex]; 
    if ((bool)therow.Cells["Sealed"].Value == true) 
    { 
     therow.DefaultCellStyle.BackColor = Color.Pink; 
    } 
    if (therow.Cells["Database"].Value as string == "PNG") 
    { 
     therow.DefaultCellStyle.BackColor = Color.LightGreen; 
    } 
} 

一切都很正常,當我處理CellFormatting,整個窗體的Paint事件似乎被關閉。後

Menu bar picture http://img213.imageshack.us/img213/2430/menubar.jpg

頂部是一個搜索之前,底部:光標停在文本框中閃爍,窗體的MenuStrip中是這樣的。菜單欄不會重新繪製,直到將鼠標懸停在菜單項的位置上,然後當鼠標移出菜單欄時,最後要突出顯示的項目將保持這種狀態。移動窗體似乎會導致它重新繪製,但問題依然存在。

在datagridview代碼中註釋掉resultsGridView.CellFormatting行可以完全解決問題。

我畫的單元格錯了,還是有其他我需要處理的東西?

回答

1

您可能在此事件中導致異常。我不確定處理是如何定義的,但用try catch來代碼是第一步。

try 
{ 
    int rowIndex = e.RowIndex; 
    .... 
} 
catch(Exception ex) 
{ 
    System.Diagnostics.Trace.Error(ex.message); 
} 

第二次看,我不認爲therow.Cells["Sealed"]將工作。嘗試像therow.Cells["dataGridViewTextBoxColumn2"]。單元格索引爲列名稱,而不是DataPropertyName

+0

「密封」部分不是數據屬性,而是數據庫中的布爾條件。我正在處理的程序會搜索一個名稱,並可以顯示我們的部門案例文件是否已被封存。 – 2009-12-01 21:11:04

+0

沒有例外。我在格式化事件的開始處添加了'Systems.Diagnotics.Trace.WriteLine(「start」)',並且它正在運行一個LOT,即使在單元已經顯示並且沒有其他事情發生之後。 – 2009-12-01 21:16:59

+0

但是「密封」了Dgv Column對象的名稱? – 2009-12-01 21:37:29