I am trying to filter a ListBox based on the presence of a string. Basically, if there is a ListItem that doesn’t contain the string then I want to remove all ListItems that do contain the string. Here is what I have tried:
Dim Item As ListItem
For Each Item In CtheList.Items
If Item.Text.IndexOf("W:") = -1 Then
CtheList.Items.Remove(Item)
End If
Next
Which is apparently a no-no as it generates the error: Collection was modified; enumeration operation may not execute.
I have also tried:
Dim Item As ListItem
For Each Item In CtheList.Items
If Item.Text.IndexOf("W:") = -1 Then
Dim i As Integer
For i = 0 To CtheList.Items.Count - 1
If CtheList.Items.Item(i).Text.IndexOf("W:") > -1 Then
CtheList.Items.RemoveAt(i)
End If
Next i
End If
Next
Which generates an index out of range exception.
Any help is greatly appreciated.
Try reversing your loop, i.e. start from the end of the list. That way, deleting items won’t shift the index of the remaining items you still have to check (which is the cause of your out of range exception).
The first way causes a problem because you’re modifying the list while iterating over it. And that is, as you said, a big no-no.