Click here to Skip to main content
15,881,715 members
Articles / Data binding
Tip/Trick

Difference between ListBox and CheckedListBox DataBinding

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
15 Aug 2011CPOL 29.7K   3   1
The difference between ListBox and CheckedListBox DataBinding.

Thought I would post this tip as it took me a little while to find the answer.


I had sucessfully bound my custom collection class to a ListBox control on a WinForm. However, when I attempted to bind to a CheckedListBox, it was populated with what appeared to be the ToString method of the collection's items, instead of the property specified for the DisplayMember.


I had read previously (http://msdn.microsoft.com/en-us/magazine/cc163630.aspx#S4[^]) that it is more efficient to set the DisplayMember and ValueMember properties before settings the DataSource property. Doing so prevents control refreshes.


However, a CheckedListBox does not display correct values unless the DataSource is set first.


E.g.:


VB
With ListBox1
  .DataSource = Nothing
  .DisplayMember = "Source"
  .ValueMember = "Destination"
  .DataSource = MyCollection
End With

With CheckedListBox1
  .DataSource = Nothing
  .DataSource = MyCollection
  .DisplayMember = "Source"
  .ValueMember = "Destination"
End With

Hope this saves someone some time!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer Computer Station (Cymru) Ltd.
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 Wow, that is a subtle problem. Thank... Pin
Dr.Walt Fair, PE15-Aug-11 13:24
professionalDr.Walt Fair, PE15-Aug-11 13:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.