Problem looping through listbox to delete item

  • Thread starter Thread starter VB Programmer
  • Start date Start date
V

VB Programmer

Here's the code:
For Each li As ListItem In Me.lstAssignedEmailAddresses.Items
If li.Selected = True Then
Me.lstAssignedEmailAddresses.Items.Remove(li)
End If
Next

When I remove an item I get this error:
System.InvalidOperationException: Collection was modified; enumeration
operation may not execute. at
System.Collections.ArrayListEnumeratorSimple.MoveNext()

I think its because I'm changing the collection while trying to loop through
it.

Any ideas for a workaround?

Thanks.
 
That's correct. You cannot change a collection while you are looping
through it.

However, a simple change can allow you to do this:

dim alItemsToDelete as ArrayList = new ArrayList()
For Each li As ListItem In Me.lstAssignedEmailAddresses.Items
If li.Selected = True Then
alItemsToDelete.Add(li)
Me.lstAssignedEmailAddresses.Items.Remove(li)
End If
Next
For Each li as ListItem In alItemsToDelete
Me.lstAssignedEmailAddresses.Items.Remove(li)
Next

Hope this helps

Ben Lucas
Lead Developer
Solien Technology, Inc.
www.solien.com
 
Thanks!
Ben Lucas said:
That's correct. You cannot change a collection while you are looping
through it.

However, a simple change can allow you to do this:

dim alItemsToDelete as ArrayList = new ArrayList()
For Each li As ListItem In Me.lstAssignedEmailAddresses.Items
If li.Selected = True Then
alItemsToDelete.Add(li)
Me.lstAssignedEmailAddresses.Items.Remove(li)
End If
Next
For Each li as ListItem In alItemsToDelete
Me.lstAssignedEmailAddresses.Items.Remove(li)
Next

Hope this helps

Ben Lucas
Lead Developer
Solien Technology, Inc.
www.solien.com
 
As someone else said, you can't modify a collection while looping through
it.

However, if you don't use an enumerator, but just use a regular for loop,
that will work fine.
 
Back
Top