How to remove selected items from a listbox

marky picture marky · Feb 1, 2017 · Viewed 7.8k times · Source

This is for a VB.NET 4.5 project in VS2015 Community.

I am trying to remove certain selected items from a listbox, but only if the selected item meets a condition. I've found plenty of examples on how to remove selected items. But nothing that works with a condition nested in the loop going through the selected items (at least, I can't get the examples to work with what I'm trying to do...)

Here's my code:

    Dim somecondition As Boolean = True
    Dim folder As String
    For i As Integer = 0 To lstBoxFoldersBackingUp.SelectedItems.Count - 1

        If somecondition = True Then
            folder = lstBoxFoldersBackingUp.SelectedItems.Item(i)
            Console.WriteLine("folder: " & folder)
            lstBoxFoldersBackingUp.SelectedItems.Remove(lstBoxFoldersBackingUp.SelectedItems.Item(i))
        End If
    Next

The console output correctly shows the text for the current iteration's item, but I can't get the Remove() to work. As the code is now, I get the console output, but the listbox doesn't change.

Answer

LarsTech picture LarsTech · Feb 1, 2017

Removing items changes the index position of the items. Lots of ways around this, but from your code, try iterating backwards to avoid that problem. You should also remove the item from the Items collection, not the SelectedItems collection:

For i As Integer = lstBoxFoldersBackingUp.SelectedItems.Count - 1 To 0 Step -1
  If somecondition = True Then
    folder = lstBoxFoldersBackingUp.SelectedItems.Item(i)
    Console.WriteLine("folder: " & folder)              
    lstBoxFoldersBackingUp.Items.Remove(lstBoxFoldersBackingUp.SelectedItems(i))
  End If
Next