How to remove text from a list box

2019-09-02 18:19发布

问题:

I am trying to make an app in Visual Basic that allows an user to type in text and add it to the list as well as remove items from the list. My problem so far is that I can't remove the items, I can add them, just not remove them. My code is as follows:

Public Class Form1
Public Listed As String
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)                        Handles btnAdd.Click
    Dim Prompt As String = "Enter Items To Add Here"
    Listed = InputBox(Prompt) 'Listed is the text from the input box
    lstBox.Items.Add(Listed).ToString() 'lstBox is ListBox1


End Sub

Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)             Handles btnRemove.Click
    With lstBox
        .SelectedItem.Remove(Listed)
    End With
End Sub
End Class

回答1:

ListBox items do not have a Remove method. You should use the Remove method of the ListBox's Items collection.

lstBox.Items.Remove(lstBox.SelectedItem) ' Removes the currently selected item from lstBox


回答2:

Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)               Handles btnRemove.Click
    With lstBox
        .Items.Remove(lstBox.SelectedItem)
      '/.Items.Remove(lstbx.SelectedItems)
    End With
End Sub