We help IT Professionals succeed at work.

Get selected indexes of a checkboxlist using linq

Focker513
Focker513 asked
on
I have an event on a checkboxlist that I would like to grab all selected indexes.

However, when casting a listitem I do not see a selected index option.

Do you have any ideas how to get the selected index ?

IEnumerable<int> checkedItems = chkTemp.Items
                            .Cast<ListItem>()
                            .Where(item => item.Selected)
                            .Select(item => int.Parse(item.Value)); // need item.Index not value
Comment
Watch Question

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

Author

Commented:
So Item.Value is indeed the index of the item?


Commented:
oops should have read a bit more of your query. why don't you 'select item' and then iterate thorugh the item collection and get the index. CheckBoxList1.Items.IndexOf(itemiterator)

Author

Commented:
Okay that looks like the only way.

So what would the iterator code look like in your example?
Commented:

IEnumerable<ListItem> allChecked = (From item As ListItem In CheckBoxList1.Items _
                              Where item.Selected = True _
                              Select item)
dim lstItem as ListItem

for each listitem in allchecked
     dom something with  CheckBoxList1.Items.IndexOf(lstItem)
next

Open in new window