ListBox DataSource property

The ListBox control has a property called “DataSource”.  You can set the DataSource to a list of items and voila!  they are all magically displayed in the listbox.  This initially seems very cool, but it turns out to only work in limited situations.

List<MyObjectName> MyObjectList; 

listBox1.DataSource = MyObjectList; 
listBox1.DisplayMember = "SomePropertyName";  // property name from the object

When it works: 

  • Really, it’s only good for static lists of items.   For example, a list of options or a data table.

When it doesn’t work:

  • It doesn’t work for Dictionaries or other collections that don’t support IList
  • It doesn’t work if you are changing the items in the list.  You can work around this by setting the DataSource to null,  then changing the list, then setting it to the list, then refreshing.  Or I read that you can use a BindingList.  But in essence this means that you are just wrestling with the feature, and it might be easier to turn it off and just manage the listbox yourself.

One feature of the ListBox that I really, really like is that you can populate it with objects and tell it which property of the object to display.  Now, that’s useful.  Remember that it has to be a property, not a field.


Post a Comment

Required fields are marked *

%d bloggers like this: