繁体   English   中英

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

[英]How to detect cell value changed datagridview c#

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

我有一个绑定到BindingList<T>对象的DataGridView (它是一个自定义对象列表;也继承了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;
        }
    }

当我的DataSource以编程方式更改时,我无法让DataGridView引发事件 - 这是设计的。

我能想到满足您需求的最佳方法是将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可能是最好的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM