Hi!

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

Listbox1.Items.Add(Textbox1.Text)
Listbox2.Items.Add(Textbox2.Text)
Listbox3.Items.Add(Textbox3.Text)

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?

Recommended Answers

All 2 Replies

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
        listbox1.Remove(i)
        Exit For
    end if
    i+=1
next 
end sub


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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.