This tutorial will show how to add items to a ListBox control in Visual Basic.NET. A list box displays a list of items that you can select one or more items from. The ListBox class has a method called Add that takes in a parameter as a string and adds it to the ListBox. In the example below, we will create a ListBox with items and add a Button that when clicked will add what is written in the TextBox into the ListBox.

Setting Up

If you have not done so already, create a new web site. To do so, open Visual Studio and click File > New > Web Site. Using ‘Visual Basic’ as the template, select ASP.NET Empty Web Site, name the web site AddToListBoxControl-VB and click OK. Now right click the web site name and click Add New Item. Again, use ‘Visual Basic’ as the template, select Web Form, leave the form name as Default.aspx and click add.

Step One

Open Default.aspx in source view and add a ListBox control inside the div tags. To add items in the ListBox on load time, we can use the ListItem template to write items. In this example we will add breeds of dogs into the ListBox. Next we will add a TextBox and Button control below the ListBox.

Also make sure to change the text of the Button control to “Add” so it makes more sense to the user what it does.

Step Two

Now that we have the code done in the front end, we have to write code in the code behind that will add an item to the ListBox when the button is clicked. Switch to design view of Default.aspx and double click the Add button to generate a click event in the code behind. You should have a Button1_Click event in Default.aspx.vb that runs code each time the Add button is clicked. Since we want to add items from the TextBox into the ListBox, we must access the ListBox class methods. To do this, we type the ID of the ListBox control and look for Items, we then look for the Add method and insert the text in the TextBox.

Output

Run the web page and you should see a a ListBox with “Labrador Retriever, Yorkshire Terrier, German Shepherd, and Golden Retriever” in it. Add “Beagle” in the TextBox and click the Add button to add it to the ListBox.

listbox 1

listbox 1

Thanks for reading and make sure to download the source files to get a better understanding of how the code works.

Download Source Files