【问题标题】:Retrieve Databound List<T> from ListBox从 ListBox 中检索数据绑定列表<T>
【发布时间】:2023-03-28 03:37:01
【问题描述】:

所以这是一个非常简单的问题,以前从未有人问过,或者以前有人问过,但我问错了问题。

假设我在 WinForm 中将 List&lt;MyObject&gt; 数据绑定到 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

有没有一种有效的方法来做到这一点?还是我应该保留原来的列表?

【问题讨论】:

    标签: c# .net winforms listbox databound


    【解决方案1】:

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

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

    【讨论】:

    • 工作就像魅力!当我单步执行代码时,我看到了DataSourceList 属性,但我不太清楚如何掌握它。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    相关资源
    最近更新 更多