1
foreach(Listitem item in CheckboxList1.Items)
{
      if(item.Selected == true)
      { 
           return true;
      }
}
return false;

Is there a better way to check if all checkbox selected is false?

2 Answers2

3

You could use LINQ very easily:

return CheckboxList1.Items
                    .Cast<ListItem>()
                    .Any(item => item.Selected);

(The call to Cast is required because ListItemCollection doesn't implement IEnumerable<T>, only the nongeneric collection interfaces.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • can anyone help me with this question too... http://stackoverflow.com/questions/4590378/asp-net-treeview-and-jquery/4590397#4590397 or http://stackoverflow.com/questions/4586915/jquery-treeview-via-asp-net –  Jan 04 '11 at 08:04
  • Ok, now the more general question.. _would you_ use LINQ instead of vanilla for? – bobobobo Jan 04 '11 at 13:23
  • @bobobobo: For this situation? Absolutely. It expresses what's going on more clearly, IMO. – Jon Skeet Jan 04 '11 at 13:36
1

If you want to check if ALL checkboxes are checked/unchecked you should use:

return CheckboxList1.Items
                    .Cast<ListItem>()
                    .All(item => item.Selected == False);//or True

Or Am I wrong ?

According to MSDN The overload of Any(Of TSource)(IEnumerable(Of TSource), Func(Of TSource, Boolean)) will return true on any item fullfilling the predicate.

RizzCandy
  • 121
  • 9