Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove selected items from a listbox

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.

like image 913
marky Avatar asked Feb 01 '17 20:02

marky


People also ask

How do I add and remove items from ListBox?

When a user enters some text into a TextBox and clicks on the add Button, text will be shown in the ListBox. After that, select text from the ListBox and click on the Delete Button to remove the text from the ListBox control.

How do you clear a ListBox?

If we want to clear the items in the Listbox widget, we can use the delete(0, END) method. Besides deleting all the items in the Listbox, we can delete a single item as well by selecting an item from the Listbox, i.e., by using currselection() method to select an item and delete it using the delete() function.


2 Answers

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
like image 58
LarsTech Avatar answered Sep 23 '22 09:09

LarsTech


You can simply use this in order to remove a selected item from the listbox ListBox1.Items.Remove(ListBox1.SelectedItem)

I hope this was helpful.

like image 23
Robert mbulanga Avatar answered Sep 22 '22 09:09

Robert mbulanga