【问题标题】:DataGridView & BindingList : How to check if cell value has changed?DataGridView & BindingList:如何检查单元格值是否已更改?
【发布时间】:2011-12-04 10:19:05
【问题描述】:

我已将 DataSource 设置为 myBindingList 的 datagridview。 列表项实现 INotifyPropertyChanged,因此 datagridview 自动响应列表中的更改。

现在我必须计算一些 datagridview 列的摘要。

应该在以下情况下完成:

  • 数据源更改(OnDataSourceChanged)
  • 单元格值变化(OnCellValueChanged)

第一个很清楚,但我对第二个有一个小问题。

OnCellValueChanged 在用户通过控件或 on 更改单元格的值时触发:

myDataGridView.Rows[x].Cells[y].Value=newValue;

但是呢:

myBindingList[myInvoice].Property1=newValue;

DataGridView 自动刷新 (INotifyPropertyChanged) 但它不会触发 OnCellValueChanged 事件。

知道如何从我的 DataGridView 中获取此类信息吗? 它必须在 DataGridView 级别完成,因为我正在编写自己的扩展 dgv 的控件。

感谢您的帮助。

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    我能想到的最接近的解决方法是使用 BindingSource 作为数据源,然后在您的自定义 DataGridView 中引发您自己的事件以响应 BindingSource ListChanged 事件。

    我可能会像这样覆盖 OnDataSourceChanged:

    public event EventHandler CustomCellValueChanged;
    
    protected override void OnDataSourceChanged(EventArgs e)
    {
        bs = this.DataSource as BindingSource;
    
        if (bs == null)
        {
            throw new ArgumentException("DataSource must be a BindingSource");
        }
    
        bs.ListChanged += new System.ComponentModel.ListChangedEventHandler(bs_ListChanged);
    
        base.OnDataSourceChanged(e);
    }
    
    void bs_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e)
    {            
        if (CustomCellValueChanged != null)
        {               
            CustomCellValueChanged(this, new EventArgs());
        }
    }
    

    这样做的问题是(我能想到的)无法获得正确的单元格属性,因此您必须重新评估所有列,而不仅仅是包含更改的列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多