[英]DataBinding of DataGridView and List<> with BindingSource
我试图弄清楚如何使用BindingSource
数据绑定工作我希望在更新列表时使用List<>
的内容填充DataGridView
。
当我检查调试器时,我可以看到List
增长并验证它是否被填充。 我认为BindingSource
会在更改List
时触发事件。 但没有一个是可用的。 如何更改基础列表时收到通知?
我按照说明操作,并提供以下测试代码:
Data d;
BindingSource bs;
public Form1()
{
InitializeComponent();
bs = new BindingSource();
d = new Data();
}
private void Form1_Load(object sender, EventArgs e)
{
bs.DataSourceChanged += new EventHandler(bs_DataSourceChanged);
bs.ListChanged += new ListChangedEventHandler(bs_ListChanged);
bs.DataMemberChanged += new EventHandler(bs_DataMemberChanged);
bs.CurrentChanged += new EventHandler(bs_CurrentChanged);
bs.CurrentItemChanged += new EventHandler(bs_CurrentItemChanged);
bs.DataSource = d.list;
dataGridView1.DataSource = bs;
}
// ... all the handling methods caught with a break point in VS.
private void button1_Click(object sender, EventArgs e)
{
d.addOneItem();
}
List<T>
不支持更改事件; BindingList<T>
将是支持此场景的良好替代品,如果您的类型T
实现了INotifyPropertyChanged
,它还支持项目级别的更改事件。
在3.0及以上版本中,还有ObservableCollection<T>
,其作用类似于BindingList<T>
。 这一切都归结为IBindingList
, IBindingListView
等接口。
来自评论; 添加Find
to BindingList<T>
的2.0 / 3.0示例:
public class MyBindingList<T> : BindingList<T>
{
public T Find(Predicate<T> predicate)
{
if (predicate == null) throw new ArgumentNullException("predicate");
foreach (T item in this)
{
if (predicate(item)) return item;
}
return default(T);
}
}
请注意,在3.5(或带有LINQBridge和C#3.0的.NET 2.0 / 3.0)中,您不需要这样做 - 任何LINQ扩展方法都会做同样的事情。
如果您希望在更改属性时收到通知,则需要实现INotifyPropertyChanged
请看这里的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.