[RESOLVED] How can I search for and delete certain ListItems?
Still working on the Pod Player rewrite, but I have a problem. When a user clicks on an item in the Genre list, the program is supposed to check the fourth ListSubItem in each ListItem in the lstSong ListView control and compare it with the selected item in the ListBox lstGenre. If the texts match, leave the ListItem alone. If they are different, remove the entire ListItem in lstSong. I'm trying to do that with this code:
Code:
Dim i
For i = 1 To lstSong.ListItems.Count
If lstSong.ListItems.Item(i).ListSubItems.Item(4).Text <> lstGenre.List(lstGenre.ListIndex) Then
lstSong.ListItems.Remove i
End If
Next i
However it removes only one ListItem in lstSong and throws up an "Index out of bounds" error. How can I get it to work right?
Re: How can I search for and delete certain ListItems?
Yes this will happen because when you remove an item the listindex of all items which come after will change by 1 So if you remove item 5 of 10 then what was item 6 becomes item 5 and there is no item 10, since your code will go on to 6 you will be skipping over item 6 which is now 5 and so on.
The simple way is to start at the other end of the list and work backwards avoiding these issues.
Code:
Dim i
For i = lstSong.ListItems.Count to 1 Step -1
If lstSong.ListItems.Item(i).ListSubItems.Item(4).Text <> lstGenre.List(lstGenre.ListIndex) Then
lstSong.ListItems.Remove i
End If
Next i
Re: How can I search for and delete certain ListItems?
Thanks, DataMiser! That fixed my problem!