How to Add Items to a ListBox in Visual Basic.NET
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.
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.
<asp:ListBox ID="ListBox1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Add" />
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.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.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.
Before Adding Beagle After Adding Beagle
Thanks for reading and make sure to download the source files to get a better understanding of how the code works.