1

So here's a question that's either so extremely simplistic that it has never been asked before or else it has been asked before, but I'm asking the question wrongly.

So say I am databinding a List<MyObject> to a ListBox control in a WinForm.

Like so:

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

Then say I later want to obtain access to that databound list.

I thought that something like this would work...

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

In Visual Studio, I can clearly see that the DataSource property of myListBox contains a List of MyObjects, however, the cast results in an InvalidCastException.

Is there an effective way to accomplish this? Or should I just hold onto the original list?

Derek W
  • 9,708
  • 5
  • 58
  • 67

1 Answers1

3

myListBox.DataSource is a BindingSource, not the List<T>. You need to get the binding source, then extract out the data from the List property:

var bs = (BindingSource)myListBox.DataSource;
List<MyObject> results = (List<MyObject>)bs.List;
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Worked like charm! I saw the `List` property of `DataSource` when I was stepping through the code, but I didn't quite know how to get a hold of it. Thank you very much! – Derek W Sep 03 '13 at 16:49