如何检测单元格值改变datagridview c#

对SOF的类似问题似乎没有明确的答案。

我有一个绑定到BindingList对象的DataGridView (它是一个自定义对象列表;也inheritance了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) { DataGridViewCellStyle cellStyle = new DataGridViewCellStyle(); cellStyle.ForeColor = Color.Red; dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = cellStyle; } } 

我不知道如何让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,它将使用自己的ListChanged事件传播NotifyPropertyChanged事件。 在一个更可能更清晰的MVVM场景中,但在WinForms中,BindingSource可能是最好的。