I'm searching for a way to delete an Item from a collection in a list box...


Adding an item in a listbox is easy, but deleting it, the way I want it to.. T_T nah! dunno.. or maybe i'm just plain stupid.

I want the user to be able to delete an Item based on what he clicked. I found this code, but this is only if you know what will be the items in the collection:

object.Remove({Index | Key})

can anyone suggest a method on how to do it?

This should work for removing one item at a time: myListBox.Itens.RemoveAt(myListBox.SelectedIndex).

If you want to enable mutiple selection/deletion you'll need to loop the SelectedIndices property.

object.Remove({Index | Key})

In this case object is your listbox, Remove is of course what you are doing to the listbox, now you can either specify the Index i.e. the position of the item in the listbox that you wish to remove or, the Key of the item which really depends on what you have in the listbox.

sub RemovebyIndex (byRef ListItem as String)
dim i as integer = 0
'assume your listbox is a list of strings....

For each item as object in listbox1.items
    if item.tostring = ListItem then
        Exit For
    end if
end sub

sub RemovebyKey (byref ListItem as String)
For each item as object in listbox1.items
    if item.Tostring  = ListItem then
        exit for
    End if
end sub

I placed the remove by key example in a loop to ensure the target item was in the list.

This article has been dead for over six months. Start a new discussion instead.