2013-10-11 53 views
1

我在处理datagridView中的数据修改时遇到了小问题。 我一个DataSource绑定到DataGridView就像这样:处理ObservableCollection中的更改

 private void Form1_Load(object sender, EventArgs e) 
    { 
     var customersQuery = new ObservableCollection<Payment>(context.Payments); 
     customersQuery.CollectionChanged += new NotifyCollectionChangedEventHandler(customerQuery_Changed); 
     dataGridView1.DataSource = new BindingSource() { DataSource = customersQuery }; 

    } 
    OrdersDataModelContainer context = new OrdersDataModelContainer(); 

,我处理类似下面的变化:

private void customerQuery_Changed(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) 
    { 
     if (e.Action == NotifyCollectionChangedAction.Add) 
     { 
      foreach (Payment p in e.NewItems) 
      { 
       context.Payments.Add(p); 
      } 
     } 
     if (e.Action == NotifyCollectionChangedAction.Remove) 
     { 
      foreach (Payment p in e.OldItems) 
      { 

       context.Payments.Remove(p); 
      } 
     } 
     context.SaveChanges(); 
    } 

删除的作品,但不添加这么好。当我点击新行时,添加动作被称为co我得到异常,因为单元格是空的。简单地说,我可以在插入完成后改变行为来调用Add,并切换到下一行? 另一个问题是修改现有的数据行。只有在插入新数据后才更新数据库。

任何人都可以给我解决方案或点我应该搜索它?

回答

1

On CollectionChanged插入新的空元素。 在PropertyChanged中向元素插入值。

+0

它的工作原理。谢谢。但是还有没有更“优雅”的方式? – szpic

+0

我试图找到绑定选项,即在添加一个之后,“在未更新集合上从新行更新集合”,但没有看到这样的结果。空行出现在网格上时创建空实体,更新值,更新时看起来足够优雅。 – Nikita

+0

是的。你是对的,但我必须再处理一个选项。当有人决定添加newRow然后将其留空时删除:) – szpic

1

您可以使用下面的类:

public class MyCollection<T> : System.Collections.ObjectModel.ObservableCollection<T> 
{ 
    public event CollectionChangeEventHandler RealCollectionChanged; 

    protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) 
    { 
     base.OnCollectionChanged(e); 
     if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add && e.NewItems.Count > 0) 
     { 
      this.OnRealCollectionChanged(e.NewItems[0]); 
     } 
    } 

    protected virtual void OnRealCollectionChanged(object element) 
    { 
     if (this.RealCollectionChanged != null) 
     { 
      this.RealCollectionChanged(this, new CollectionChangeEventArgs(CollectionChangeAction.Add, element)); 
     } 
    } 
} 

本次活动将在标准相继被抛出,但是这是其可以在抛出的最新点。

+0

谢谢!说实话,我不明白这段代码片段,但会读到它:) – szpic