Checking if CheckBoxList has any selected values

房东的猫 提交于 2019-12-01 14:26:39

问题


I would like to know the fastest/easiest way to check if a CheckBoxList control has any checked items or not, I'm talking about an entire checkbox list as a whole, not a single checkbox.


回答1:


This one should help:

bool isAnySelected = checkBoxList.Items.Any(i => i.Selected);

.Any is a Linq extension method, so you will need the System.Linq or .System.Linq.Extensions reference (can't remember which) in your code-behind.




回答2:


The Linq extension method is neat, but you can also just check the SelectedIndex:

bool isAnySelected = CheckBoxList1.SelectedIndex != -1;

If nothing is checked, the SelectedIndex is -1.




回答3:


For anyone coming here 5 years after the selected answer, the Items collection is not enumerable therefore .Any(...) will not work. You can, however, do the following:

If cblCheckboxList.Items.Cast(Of ListItem).Any(Function(x) x.Selected) then...



回答4:


The selected answer is great but now you can simply modify the code by adding OfType function. check the following:

bool isAnySelected = checkBoxList.Items.OfType<ListItem>().Any(i => 
i.Selected);

I hope this helps.



来源:https://stackoverflow.com/questions/3486847/checking-if-checkboxlist-has-any-selected-values

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