How to Add and Remove Items in Visual Basic .Net Listbox

Problem:

Create a Windows Form Application program in visual basic .net that will allow the user to add and remove item(s) in listbox.

Description:

Windows form application program allows us to create application with windows user interface.

Search Listbox

This tutorial will allow the user to enter a string, a name to be specific in the textbox and save or add it in the listbox. All the names added will be displayed in the listbox and the user will be able to select and delete a name in the list.

The tutorial starts here:

  1. Open your Microsoft Visual Studio 2010.
  2. On the File menu select New Project.
  3. Select Visual Basic, Windows Form Application then click OK.
  4. We will now design and add controls to the form.
    1. 1 textbox
    2. 2 labels
    3. 2 buttons (Add and Remove button)
    4. 1 listbox
  5. This is how we design the form. (Feel free to layout your own).
    vbnetlistbox1

Figure 1. Design of the Form

  1. Double click the Add button and paste the code.
If TextBox1.Text = "" Then
MessageBox.Show("Please enter a text in textbox")
TextBox1.Focus()
Else
ListBox1.Items.Add(TextBox1.Text)
TextBox1.Clear()
End If

Code Explanation:

The code above will add the names to the listbox. The program will display an error message if you leave the textbox empty. The name you have entered will be added to the list and the textbox will be cleared to allow another entry.

  1. Double click the Delete button (please refer to the Figure 1) and paste the code
If ListBox1.SelectedItem = "" Then
MessageBox.Show("please select item to remove")
Else
ListBox1.Items.Remove(ListBox1.SelectedItem)
End If

Code Explanation:

The code will remove the selected item from the list, but it will first determine if you have selected an item on the list to be deleted or removed.

  1. On the DoubleClick event of the listbox, kindly paste the code.
MessageBox.Show("selected: " & ListBox1.SelectedItem.ToString)

Make sure the code will be placed between these lines:

Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick

End Sub

Code Explanation:

A message box will be displayed together with the item you have selected on the list.

Note: the code will be triggered when the user will double clicke the listbox.

  1. Save and test the project.

Just follow the 9 simple steps, Happy Programming!

You are free to comment and if you have found trouble and difficulties with the tutorial you can email us or post your concern on our facebook page.

We will try our best to answer your queries.

vbnetlistbox2
Download

, , ,

Post navigation