A question came up recently on the NZ dot Net mailing list:

Any one use listbox.DataSource = myList for data binding to a List box?
I cannot refresh the data source ‘myList’. If I use the following code to update the data source:

listbox.DataSource = null;
listbox.DataSource = newList;

The items in the listbox are object types rather than data values.

Can any one tell me how to refresh the data in the list box when binding to the control?

My reply was:

What works for me is to use a BindingList<T> to wrap your original list.

// Get list of people from somewhere
List<Person> people = ...

// Create a wrapper list
BindingList<Person> boundPeople = new BindingList<Person>(people);

// Bind to listbox
Listbox.DataSource = boundPeople;

// Make changes to people
MessAroundWithStuff(people);

// Update the listbox
boundPeople.ResetBindings();

The key is that the BindingList<T> constructor shown creates a WRAPPER collection around the original list. It doesn’t create a new list containing the same elements. (I’ve never seen this documented, but have verified with Reflector).

I thought that it would be worth following up on this with a small demo - see the attached file ListBindingDemo.zip for a working example.

Download

List Binding Demo

Next Post
Upgradable MSI installations with WiX  12 Sep 2008
Prior Post
Reflector  28 Aug 2008
Related Posts
Error assertions  26 Apr 2025
Browsers and WSL  31 Mar 2024
Factory methods and functions  05 Mar 2023
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Archives
September 2008
2008