Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple checked items from CheckedListBox

I know how to remove a single checkedItem from checkedlistbox. But now, I want to remove all the checked items in one go.

I tried this:

foreach (var item in List_Frente.CheckedItems)
            {
                List_Frente.Items.Remove(item);
            }

But as you probably know, it gives me an error,saying that, List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change. How may I remove all checkeditems with a single click ?

like image 753
Ghaleon Avatar asked Jan 29 '13 19:01

Ghaleon


2 Answers

you could do something like this:

foreach (var item in List_Frente.CheckedItems.OfType<string>().ToList())
{
    List_Frente.Items.Remove(item);
}

If you want to write it all in one line:

List_Frente.CheckedItems.OfType<string>().ToList().ForEach(List_Frente.Items.Remove);

This only works if your items are of the same type, of course. Looks still crude, though.

Edit-Explanation: ToList() creates a new list and thus, the original CheckedItems list can be changed, as the enumerator now enumerates our newly created list, not the original. The OfType<string>() is only there because we need something to call ToList() on.

like image 115
Jobo Avatar answered Sep 18 '22 21:09

Jobo


while (checkedListBox.CheckedItems.Count > 0) {
   checkedListBox.Items.RemoveAt(checkedListBox.CheckedIndices[0]);
}
like image 24
Chico Maia Avatar answered Sep 20 '22 21:09

Chico Maia