【发布时间】:2013-01-28 21:20:24
【问题描述】:
我想在 Windows 窗体应用程序的 DataGridView 中显示自定义集合。这个自定义集合实现了ICollection 和IEnumerable。我设置了一个BindingSource,将集合用作 .DataSource 属性。 DataGridView 设置为使用我的BindingSource 作为数据源。当我使用 BindingSource.Add() 方法将新项目添加到集合中时,DataGridView 会随着新项目正确更新。另一方面,BindingSource 数据源却没有:
MyCustomCollection myCollection = new MyCustomCollection();
myCollection.Add(myCustomObject1);
myCollection.Add(myCustomObject2);
myBindingSource.DataSource(myCollection);
myBindingSource.Add(myCustomObject3);
在上面的代码中,myBindingSource 的内部 List 包含正确数量的记录(3),DataGridView 也包含 3 条记录,但 myCollection 只包含 2 条记录。我知道更改底层 myCollection 不会更新 BindingSource 或 DataGridView,因为它不是 BindingList<T>,但我的印象是直接更新 BindingSource 将确保 myCollection 在同一时间。
有没有办法使用不是BindingList<T> 的集合并在直接与BindingSource 交互时更新它?
更新:我在所有部分(Collection、BindingSource、DataGridView)中更新数据的一种方法如下:
myCollection.Add(myCustomObject3);
myBindingSource.DataSource = null;
myBindingSource.DataSource = myCollection;
我很确定有更好的方法来解决这个问题,但这是产生我期望的结果的唯一方法。
【问题讨论】:
-
我在下面的线程stackoverflow.com/questions/35275335/…回答了这个问题
标签: c# winforms data-binding collections bindingsource