When you delete an item, the checkedItems
collection gets smaller. Just remove the first one repeatedly:
while (checkedItems.Count > 0)
{
checkedListBox1.Items.Remove(checkedItems[0]);
}
Or remove in reverse order:
for (int i = checkedItems.Count; i > 0; )
{
checkedListBox1.Items.Remove(checkedItems[--i]);
}
Even better, use CheckedIndices, which avoids the need to search for matching items and confusion in the case of duplicates:
var checkedItemIndices = checkedListBox1.CheckedIndices;
for (int i = checkedItemIndices.Count; i > 0; )
{
checkedListBox1.Items.RemoveAt(checkedItemIndices[--i]);
}