检索数据绑定列表<;T>;来自ListBox

本文关键字:gt 来自 ListBox lt 数据绑定 列表 检索 | 更新日期: 2023-09-27 18:30:07

所以这里有一个问题,要么过于简单,以前从未被问过,要么以前被问过了,但我问错了。

假设我正在WinForm中将List<MyObject>数据绑定到ListBox控件。

像这样:

List<MyObject> list = new List<MyObject>();
// add some MyObjects to list...
myListBox.DataSource = new BindingSource(list, null);

然后说我以后想访问那个数据绑定列表。

我以为这样的事情会奏效。。。

List<MyObject> results = (List<MyObject>)myListBox.DataSource;

在Visual Studio中,我可以清楚地看到myListBoxDataSource属性包含MyObjects的列表,但是,强制转换会导致InvalidCastException

有没有有效的方法来实现这一点?还是我应该保留原始列表?

检索数据绑定列表<;T>;来自ListBox

myListBox.DataSourceBindingSource,而不是List<T>。您需要获取绑定源,然后从List属性中提取数据:

var bs = (BindingSource)myListBox.DataSource;
List<MyObject> results = (List<MyObject>)bs.List;