Winform : How toDatabind CheckedListBox if it is missing DataSource
When you decide to use CheckedListBox Control, you might expect to useDisplayMember
, ValueMember
or DataSource
property like you do for example with ListBox, but you will discover that the Intellisense is not showing those properties at all.
The good news is that even though Intellisense will not show them, the code will still compile when you type those properties by hand.
Now you might think problem solved. Well not exactly.
Microsoft is not recommending this approach. According to them, Data Binding is not supported on CheckedListBox
but since the above properties are inherited from a base class, they can not be removed, so the Microsoft just hid them.
So keep this in mind if you decide to use those properties on CheckedListBox
How do you fill the control with items without using DataSource property?
One solution of course is to use Items.Add
method to add individual item. If you already have an array or a list that contains items, you then use foreach loop and add every item with Items.Add
like this:
string[] IceCreamFlavors = {"Banana", "Chocolate", "Pistachio", "Strawberry", "Vanilla"};
foreach (var item in IceCreamFlavors)
{
checkedListBox1.Items.Add(item);
}
But there is simpler way to add items from array or a List by using Items.AddRange
method instead like this:
checkedListBox1.Items.AddRange(IceCreamFlavors);
If you want to add items from a List, just use ToArray
method:
checkedListBox1.Items.AddRange(myList.ToArray());
I hope you found this article useful. Feel free to drop a comment or connect with this blog on the social networks.