how to find if the check box list is selected or not in asp.net

心不动则不痛 提交于 2019-12-23 10:16:09

问题


How to get selected index in a check box list in asp.net. Should I loop through to find whether the list box is selected or can i get to know without doing that. I want to do this

if(Checkboxlist selected) {do this} else {do this}

how to find if the check box list is selected or not in asp.net

int roleselected = ckl_EditRole.Items.SelectedIndex;

回答1:


For CheckBoxList, SelectedIndex will give you just the first selected index in the CheckBoxList. If it's not -1, then something was selected. This may be enough for what you're looking for.

if( ckl_EditRole.SelectedIndex != -1 )
{
// Do Something
}

But, since the CheckBoxList can have multiple selections, you probably want to loop through the Items and look for the selected ones.

foreach( ListItem li in ckl_EditRole.Items )
{
    if( li.Selected )
    {
        // Do Something
    }
}



回答2:


If your intention is to get index of the selected checkbox as given by your code, you can also achieve this via Linq(without forloop) as below.

ckl_EditRoleItems.OfType<ListItem>().Where(p=>p.Selected).Select(p => ckl_EditRoleItems.Items.IndexOf(p)).ToArray<int>();

This statement will return an array of int which will contain the index of the check boxes that are selected.



来源:https://stackoverflow.com/questions/8009769/how-to-find-if-the-check-box-list-is-selected-or-not-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!