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?
Do you want to remove all items? If so, do the foreach
first, then just use Items.Clear()
to remove all of them afterwards.
Otherwise, perhaps loop backwards by indexer:
listBox1.BeginUpdate();
try {
for(int i = listBox1.Items.Count - 1; i >= 0 ; i--) {
// do with listBox1.Items[i]
listBox1.Items.RemoveAt(i);
}
} finally {
listBox1.EndUpdate();
}