【问题标题】:How to detect cell value changed datagridview c#如何检测单元格值更改datagridview c#
【发布时间】:2012-03-07 16:42:03
【问题描述】:

对于 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;
        }
    }

【问题讨论】:

  • 你并没有 100% 清楚你想要做什么。我将根据我的最佳猜测来回答,但您能否编辑您的问题以明确您想要实现的目标。
  • 对不起,我应该更清楚。用户不进行编辑。不断解析 CSV 文件以从 BindingList 添加/更新/删除对象。假设我启动程序,DGV 中只有一行。我会看到计时器每秒递增一次,当它经过 10 秒时,我想将文本的颜色更改为红色。
  • 刚刚用对你有用的东西编辑了我的答案。

标签: c# .net datagridview


【解决方案1】:

据我所知,当 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 可能是最好的。

【讨论】:

  • 抱歉拖了这么久,谢谢!我使用了 NotifyPropertyChanged 事件,现在一切正常!
猜你喜欢
  • 2017-08-02
  • 1970-01-01
  • 2011-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多