开发者

Is there a reason that ASP.NET's CheckBoxList doesn't have a SelectedItems member?

开发者 https://www.devze.com 2023-01-17 00:08 出处:网络
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 开发者_C百科the end) member which seems odd for a CheckBoxLi

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 开发者_C百科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?


Because 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.)


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);
}


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.


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();
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号