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 ?
Might be an addon for this post.
To clear all the items.
This is because you modify the list you are iterating over. Use a for-statement to prevent this from happening:
As stated in this MSDN-Article the
CheckedListBox.CheckedItemCollection
implements theIList.Remove
-method explicitly, meaning you will have to cast the instances toIList
to make this work.This works.
I aim to return with an solution that are more beautiful and less hacky.
you could do something like this:
If you want to write it all in one line:
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. TheOfType<string>()
is only there because we need something to callToList()
on.