Results 1 to 3 of 3

Thread: [RESOLVED] How can I search for and delete certain ListItems?

  1. #1

    Thread Starter
    New Member WindozeNT's Avatar
    Join Date
    Jun 2012
    Location
    Middle of nowhere
    Posts
    10

    Resolved [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?

  2. #2
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,206

    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

  3. #3

    Thread Starter
    New Member WindozeNT's Avatar
    Join Date
    Jun 2012
    Location
    Middle of nowhere
    Posts
    10

    Re: How can I search for and delete certain ListItems?

    Thanks, DataMiser! That fixed my problem!

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width