Databinding with Lists
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<> 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.
| Attachment | Size |
|---|---|
| ListBindingDemo.zip | 21.88 KB |
Recent comments
3 weeks 4 days ago
4 weeks 3 days ago
4 weeks 3 days ago
4 weeks 4 days ago
7 weeks 16 hours ago
7 weeks 3 days ago
7 weeks 3 days ago
10 weeks 1 day ago
11 weeks 3 days ago
11 weeks 4 days ago