Databinding a listbox control to an object collection

 
10 oktober 2008

When you databind an object collection to a listbox, the ToString() method is used to visualize the items in the listbox. Adding and removing items to the collection automatically updates the listbox, but changing the output of the ToString() method does not.

Strangely enough this behaviour does work as expected with the CheckedListbox control, which inherites from the ListBox control. It does not work directly, you will have to invalidate the control by calling the CheckedListBox.Invalidate() method after you have changed the collection.

The solution lies in implementing the INotifyPropertyChanged interface on the object in the collection. When you implement this interface, there is no need to call the Invalidate() method anymore, so it seems like that’s the way to go.

Code example:

List<person> people = new List<person>();
people.Add(new person(“Sjors Miltenburg”));
people.Add(new person(“Stefan Bookholt”));

listBox1.DataSource = people;
listBox1.DisplayMember = “Name”;

checkedListBox1.DataSource = people;
checkedListBox1.DisplayMember = “Name”;

//this is the point where the ListBox control will not update it’s
//appearance if the person class does not implement the
//INotifyPropertyChanged interface

people[0].Name = “Pieter Joost vd Sande”;


Werken met ?
Kijk dan bij onze mogelijkheden voor starters en/of ervaren IT'ers.


Categorieën: Development, .Net

Tags: , , , , ,