How do I iterate through a listbox without using FOR EACH

  • Thread starter Thread starter COHENMARVIN
  • Start date Start date
C

COHENMARVIN

I've been doing a simple for-each loop to remove multiple selected
items from one listbox, and to dump them in another listbox.

for each item in LeftListBox.Items
if (item.Selected = true) Then
RightListBox.Items.Add(item)
LeftListBox.Items.Remove(item)
End If
Next
The problem is that this code doesn't work because its modifying the
collection in the left listbox. I get an error such as:
"Collection was modified; enumeration operation may not execute".
I searched the internet for an explanation, and I see one person who
says that you cannot use For-each in a situation like this, instead you
should use For-Next. My question: How do you iterate through a listbox
with for-next?
Thanks,
Marvin
 
COHENMARVIN said:
I've been doing a simple for-each loop to remove multiple selected
items from one listbox, and to dump them in another listbox.

for each item in LeftListBox.Items
if (item.Selected = true) Then
RightListBox.Items.Add(item)
LeftListBox.Items.Remove(item)
End If
Next
The problem is that this code doesn't work because its modifying the
collection in the left listbox. I get an error such as:
"Collection was modified; enumeration operation may not execute".
I searched the internet for an explanation, and I see one person who
says that you cannot use For-each in a situation like this, instead you
should use For-Next. My question: How do you iterate through a listbox
with for-next?
Thanks,
Marvin

The code below should work using a While loop. Warning: Untested, but
should get you closer to what you're trying to do:

Dim blnContinue As Boolean = True
Dim lngIndex As Long

While blnContinue

If LeftListBox.Items(lngIndex).Selected Then
RightListBox.Items.Add(LeftListBox.Items(lngIndex))
LeftListBox.Items.Remove(LeftListBox.Items(lngIndex))
Else
lngIndex += 1
End If

blnContinue = (lngIndex < LeftListBox.Items.Count)

End While

Also, I don't remember offhand if the Items collection of the ListBox is
zero-based or not. The above example assumes it's zero-based.

Ben
 
Back
Top