2012-03-07 144 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

相关问题