tags:

views:

47

answers:

2

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?

+2  A: 

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.
How can I access each individual item then?
Sergio Tapia
as i said, use a for loop
Scott M.
A `while` loop might be appropriate as well. Is there a property such as `SelectedItem`? You know, it all depends on the specific collection /library that you are using.
Hamish Grubijan
thanks, i changed my answer to be more useful on your suggestion
Scott M.
+4  A: 
while(lstPhotos.SelectedItems.Count != 0)
{
    lstPhotos.Items.Remove(lstPhotos.SelectedItems[0]);
}
max