Dailycode.info

Short solution for short problems

Checked listbox: CheckItems / SelectedItems

I was working with a checked listbox and had a simple thing to do:

Save all the selected items to a string (Items are seperated by a space) in the databse. First I thought, no problem, just iterate through the list items, check if the item is selected and add it to the string.

But then I found the selecteditems property. At first I couldn’t cast it to an array, so after a little surfing I came up with this solution. I quickly found that I had to use the CheckedItems property. Because SelectedItems only gets the items that are highlighted, CheckedItems gets the items that are checked. Here the code:

string[] destination = new string[cbxlstRooms.CheckedItems.Count];
cbxlstRooms.CheckedItems.CopyTo(destination, 0);
string rooms=string.Join(" ",destination);
_study.CurrentStudy.Rooms = rooms; //this is where I set the object that is saved to the DB later.
 

And this works fine!

Here's an example of a checked list box I used:

checked listbox