4

Im using LINQ to retrive cheched Items from CheckBoxList control:

Here the LINQ :

    IEnumerable<int> allChecked = (from ListItem item in CheckBoxList1.Items
                                       where item.Selected 
                                       select int.Parse(item.Value));

My question is why item have to be ListItem type?

Michael
  • 13,950
  • 57
  • 145
  • 288

3 Answers3

4

My question is why item have to be ListItem type?

Because CheckBoxList1.Items is an ObjectCollection whose members are ListItems. That's what your linq query is working against.

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
4

The CheckedListBox was created before generics were introduced, thus the Items collection returns objects rather than the strongly typed ListItem. Luckily, fixing this with LINQ is relatively easy using the OfType() (or Cast) methods:

IEnumerable<int> allChecked = (from ListItem item in CheckBoxList1.Items.OfType<ListItem>()
                                   where item.Selected  
                                   select int.Parse(item.Value)); 
Jim Wooley
  • 10,169
  • 1
  • 25
  • 43
1

why item have to be ListItem type?

I think because CheckBoxList inherits from ListControl and Items property is inherited from ListControl

Haris Hasan
  • 29,856
  • 10
  • 92
  • 122