Cannot remove items from ListBox

2019-01-29 02:55发布

问题:

When trying to run this method I get an error:

List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.

foreach (var item in lstPhotos.SelectedItems)
{
    lstPhotos.Items.Remove(item);
}

How can I remove the selected items?

回答1:

while(lstPhotos.SelectedItems.Count != 0)
{
    lstPhotos.Items.Remove(lstPhotos.SelectedItems[0]);
}


回答2:

the foreach loop doesn't allow you to modify the collection being enumerated. if you need to modify the collection use a for loop instead.

edit:

I am leaving my original answer above, but upon coding this it became apparent that a while loop is better suited to this problem because of the dynamic length of the SelectedItems property.

while(lstPhotos.SelectedItems.Length > 0)
{
    lstPhotos.Items.Remove(lstPhotos.SelectedItems[0];
}


标签: c# listbox