2012-03-07 38 views
4

對於SOF上的類似問題,似乎沒有確定的答案。如何檢測單元格值已更改datagridview c#

我有一個DataGridView綁定到一個BindingList<T>對象(這是一個自定義對象的列表;也繼承INotifyPropertyChanged)。自定義對象每個都有一個唯一的計時器。當這些計時器通過一定的值(比如10秒)時,我想將單元格的前景色改爲紅色。

我正在使用CellValueChanged事件,但此事件似乎從未觸發,即使我可以看到計時器在DataGridView上變化。是否有我應該尋找的不同事件?以下是我的CellValueChanged處理程序。

private void checkTimerThreshold(object sender, DataGridViewCellEventArgs e) 
    { 
     TimeSpan ts = new TimeSpan(0,0,10); 
     if (e.ColumnIndex < 0 || e.RowIndex < 0) 
      return; 
     if (orderObjectMapping[dataGridView1["OrderID", e.RowIndex].Value.ToString()].getElapsedStatusTime().CompareTo(ts) > 0) 
     { 
      DataGridViewCellStyle cellStyle = new DataGridViewCellStyle(); 
      cellStyle.ForeColor = Color.Red; 
      dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = cellStyle; 
     } 
    } 
+0

你不會100%清楚你想要做什麼。我會根據我最好的猜測來回答,但是你能否編輯你的問題來說明你想要達到的目標。 – 2012-03-07 16:48:03

+0

對不起,我應該更清楚了。用戶不做編輯。不斷解析CSV文件以從BindingList 添加/更新/刪除對象。假設我開始這個程序,並且DGV中只有一行。我會看到計時器每秒遞增,當它通過10秒鐘時,我想將文本的顏色更改爲紅色。 – jpints14 2012-03-07 17:35:10

+0

剛剛編輯我的答案與應該爲你工作的東西。 – 2012-03-07 22:27:16

回答

3

有沒有辦法讓我DataGridView引發事件時,它的DataSource編程方式更改 - 這是設計。

爲了滿足您的需求,我可以想到的最佳方式是將BindingSource引入混合中 - 綁定源在其DataSource更改時引發事件。

像這樣的作品(你會明顯需要微調到您的需要):

bindingSource1.DataSource = tbData; 
dataGridView1.DataSource = bindingSource1; 
bindingSource1.ListChanged += new ListChangedEventHandler(bindingSource1_ListChanged); 

public void bindingSource1_ListChanged(object sender, ListChangedEventArgs e) 
{ 
    DataGridViewCellStyle cellStyle = new DataGridViewCellStyle(); 
    cellStyle.ForeColor = Color.Red; 

    dataGridView1.Rows[e.NewIndex].Cells[e.PropertyDescriptor.Name].Style = cellStyle; 
} 

另一種選擇通過直接訂閱的數據要做到這一點 - 如果它是一個的BindingList它會傳播完成NotifyPropertyChanged事件使用自己的ListChanged事件。在更多的MVVM場景中,可能會更乾淨,但在WinForms中,BindingSource可能是最好的。

+0

對不起,花了這麼長時間,但謝謝!我使用NotifyPropertyChanged事件,現在一切正常! – jpints14 2012-03-20 19:21:06

相關問題