Data binding a ListBox to a List<T>

C

Chris Dunaway

I have 2 list boxes on the form. Each listbox is bound to a different
List<T>. My goal is for the user to select an item in ListBox1, click
a button, and have that item moved to ListBox2.

The way I approached this was to have a populated List<T1> bound to
ListBox1. I set the DataSource, DisplayMember, and ValueMember
properties of ListBox1 and the items in the List<T1> were correctly
shown in the listBox. I bound ListBox2 to List<T2>. Since List<T2>
had nothing in it, ListBox2 correctly showed no items.

I thought that if I removed an item from List<T1>, that ListBox1 would
update to reflect that but it doesn't seem to work that way.
Similarly, I thought that by inserting an item into List<T2>, that the
ListBox2 would update to reflect the addition. It does not seem to
work that way.

How can I get the ListBoxes to update and show the current contents of
their respective List<T> objects?

Is there a way to "rebind" them?

Thanks,

Chris
 
C

Chris Dunaway

For others with this same problem, I found a solution. There are 2
ways to do it. The first is to manually rebind by doing this:

ListBox1.DataSource = null;
ListBox1.DataSource = DataSourceObject;
ListBox1.DisplayMember = "Property1";
ListBox1.ValueMember = "Property2";


Or use a BindingList<T> instead of List<T>. Then it updates
automatically.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top