Tony Yang
Tony Yang

Reputation: 21

how to remove a item in listbox in vb

the string is looks like 11,33,44 i made a split into three strings into 3 textboxes, and then when i do ListBox1.Items.Remove(ListBox1.SelectedItem) it doesn't work.

it says ss.Split(",") Object reference not set to an instance of an object.

here is my code

    Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As        System.EventArgs) Handles ListBox1.SelectedIndexChanged
    Dim ss As String = ListBox1.SelectedItem

    Dim aryTextFile(2) As String
    aryTextFile = ss.Split(",")


    TextBox1.Text = (aryTextFile(0))
    TextBox2.Text = (aryTextFile(1))
    TextBox3.Text = (aryTextFile(2))

    ss = String.Join(",", aryTextFile)

End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    ListBox1.Items.Add(TextBox1.Text + "," + TextBox2.Text + "," + TextBox3.Text)
End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click

    ListBox1.Items.Remove(ListBox1.SelectedItem)


End Sub

Upvotes: 1

Views: 12129

Answers (2)

Azoz
Azoz

Reputation: 1

Try this:

listbox.selecteditem.remove()

It will remove the selected item in the listbox.

Upvotes: 0

David -
David -

Reputation: 2031

When you remove an item from the ListBox by pressing the Button2, the SelectedIndexChanged of the ListBox1 is being called. There, the selected item will be nothing, so to solve this, add the following lines inside the SelectedIndexChanged event before assigning the string variable.

    If ListBox1.SelectedItem Is Nothing Then
        Exit Sub
    End If

Upvotes: 1

Related Questions