Reputation: 79
I have created a list box and at the moment I am trying to make it such that you can delete one item or multiple items using this code:
Private Sub Delbtn_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles Delbtn.Click
lstCountries.Items.Remove(lstCountries.SelectedItem)
lstCountries.Items.Remove(lstCountries.SelectedItems)
End Sub
However when using this I am not able to delete more than one selection at a time. What is the best way to make it so that I can delete one or more than one selection?
Upvotes: 1
Views: 4059
Reputation: 38865
First, make sure there are some things selected:
If lstCountries.SelectedItems.Count > 0 Then
' MUST loop backwards thru collections when removing
' or you will remove the wrong things, miss stuff and
' run out early
For n As Integer = lstCountries.SelectedItems.Count - 1 To 0 Step -1
' remove the current selected item from items
lstCountries.Items.Remove(lstCountries.SelectedItems(n))
Next n
End if
There is also a SelectedIndicies
Collection which would return a collection of integers of the items. If you iterate that, use .RemoveAt()
but you still need to loop backwards.
Upvotes: 2