如何检测在C#中DataGridView单元格值的变化

4

在SOF上没有关于类似问题的明确答案。

我有一个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;
        }
    }

你并没有完全清楚地表达你想要做什么。我会根据我的猜测来回答,但是你能否编辑你的问题以明确你想要实现什么。 - David Hall
抱歉,我应该表述得更清楚。用户不进行编辑。CSV文件正在不断解析以添加/更新/删除BindingList<T>中的对象。假设我启动程序,DGV中只有一行。我会看到计时器每秒递增,当它超过10秒时,我想将文本颜色更改为红色。 - jpints14
刚刚编辑了我的答案,加入了一个对你有用的内容。 - David Hall
1个回答

3

据我所知,目前没有办法使DataGridView在程序上更改其数据源时引发事件-这是设计上的限制。

我能想到的最好方法是将BindingSource引入其中 - 绑定源在其数据源更改时会引发事件。

以下代码可以实现此功能(您显然需要根据自己的需求进行微调):

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可能是最好的选择。


抱歉让你等这么久,但还是谢谢!我使用了NotifyPropertyChanged事件,现在一切都完美运行了! - jpints14

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接