Retrieve Databound List<T> from ListBox

98 views Asked by At

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?

1

There are 1 answers

1
Reed Copsey On BEST ANSWER

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;