I'm getting the error below when trying to loop through a listbox and then remove the item.
List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.
foreach (string s in listBox1.Items)
{
MessageBox.Show(s);
//do stuff with (s);
listBox1.Items.Remove(s);
}
How can I remove the item and still loop through the contents?
Everyone else has posted "going backwards" answer, so I'll give the alternative: create a list of items you want to remove, then remove them at the end:
Sometimes the "work backwards" method is better, sometimes the above is better - particularly if you're dealing with a type which has a
RemoveAll(collection)
method. Worth knowing both though.Here my solution without going backward and without a temporary list
You have to go through the collection from the last item to the first. this code is in vb
Jefferson is right, you have to do it backwards.
Here's the c# equivalent:
You can't make modification to the collection being iterated within the ForEach block.
A quick fix is to iterate over a copy of the collection. An easy way to make this copy is through the ArrayList constructor. The DataRowView objects in the copied collection will refer to, and be able to modify, the same underlying data as your code.
please read http://social.msdn.microsoft.com/Forums/en-AU/vbgeneral/thread/b4d1f649-d78a-4e5b-8ad8-1940e3379bed
Do you want to remove all items? If so, do the
foreach
first, then just useItems.Clear()
to remove all of them afterwards.Otherwise, perhaps loop backwards by indexer: