Problem looping through listbox to delete item

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.
 
B

Ben Lucas

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
 
V

VB Programmer

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
 
M

Marina

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top