1

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?

Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254
  • you may want to see http://stackoverflow.com/questions/380451/how-do-i-do-i-loop-through-items-in-a-list-box-and-then-remove-that-item – nawfal Jun 05 '13 at 13:53

2 Answers2

4
while(lstPhotos.SelectedItems.Count != 0)
{
    lstPhotos.Items.Remove(lstPhotos.SelectedItems[0]);
}
max
  • 33,369
  • 7
  • 73
  • 84
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];
}
Scott M.
  • 7,313
  • 30
  • 39