Whenever I want to get selected items I have to loop through each item and see if it's selected. They even have a SelectedItem (no "s" at the end) member which seems odd for a CheckBoxList. It seems like a logical thing to have, does anyone know why they haven't added it?
views:
44answers:
4Because they're not implementing the SelectedItem in CheckBoxList, but in ListControl that CheckBoxList inherits from. It can be argued that CheckBoxList needs to be taken back to source, as many of the ways that it is written are just not "correct" but that's a subjective argument. (this is the subject of a personal rant, I've just come across too many cases of CheckBoxList doing something obtusely and it's annoying, is all. Just not the way my mind works I suppose, and have never had others corroborate that it is annoying to them too.)
I would have to say that because the checkbox list renders individual HTML checkboxes that are not groupable like radio buttons the selected property needs to be evaluated on a item by item basis.
It is part of the documentation. Also note that the SelectedIndex
will return the item with the lowest index.
The CheckBoxList control provides a multi selection check box group that can be dynamically generated with data binding. It contains an Items collection with members corresponding to individual items in the list. To determine which items are checked, iterate through the collection and test the Selected property of each item in the list.
In addition to Dustin's en drachenstern's answers. You can roll your own :-)
public static IEnumerable<ListItem> SelectedItems(this CheckBoxList cbl)
{
return cbl.Items.Cast<ListItem>().Where(l=>l.Selected == true);
}
It's also fairly easy to subclass the CheckBoxList and implement this functionality yourself, which you can then re-use.
public class ExtendedCheckBoxList : CheckBoxList
{
public List<string> SelectedItems
{
get
{
return (from ListItem item in Items
where item.Selected
select item.Value).ToList();
}
}
}