Checking if CheckBoxList has any selected values
Asked Answered
C

4

12

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.

Cornflower answered 15/8, 2010 at 9:30 Comment(0)
L
7

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.

Lobel answered 15/8, 2010 at 9:42 Comment(0)
B
19

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.

Boff answered 1/8, 2011 at 15:27 Comment(1)
should be the selected answerNakada
L
7

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.

Lobel answered 15/8, 2010 at 9:42 Comment(0)
T
2

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...
Teapot answered 19/6, 2017 at 14:23 Comment(0)
V
2

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.

Vilma answered 13/12, 2017 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.