vbnet
  1. vbnet-listbox-control

Working with Forms and Controls in VB.NET: ListBox Control

The ListBox control in VB.NET is used to display a list of items from which the user can make a selection. It is commonly used in graphical user interfaces (GUIs) to display a list of options for users to choose from.

Syntax

To create a ListBox control in VB.NET, use the following syntax:

Dim listBox1 As New ListBox

To add items to the ListBox control, use the following syntax:

listBox1.Items.Add("Item 1")
listBox1.Items.Add("Item 2")
listBox1.Items.Add("Item 3")

To select an item in the ListBox control, use the following syntax:

listBox1.SelectedItem = "Item 2"

Example

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListBox1.Items.Add("Item 1")
        ListBox1.Items.Add("Item 2")
        ListBox1.Items.Add("Item 3")
        ListBox1.SelectedItem = "Item 2"
    End Sub
End Class

Output

The above example will create a new form with a ListBox control that displays three items ("Item 1", "Item 2", and "Item 3"). The second item ("Item 2") will be selected by default.

Explanation

In the above example, we are creating a new form and adding a ListBox control to it. We are then adding three items to the ListBox control and selecting the second item ("Item 2") by default.

Use

The ListBox control is commonly used in GUIs to provide a list of options for users to choose from. It can be used to select one or multiple items at a time, depending on the settings of the control.

Important Points

  • The ListBox control is used to display a list of items from which the user can make a selection.
  • Items can be added to the ListBox control using the Items.Add method.
  • The selected item in the ListBox control can be set using the SelectedItem property.
  • The ListBox control can be used to select one or multiple items at a time, depending on the settings of the control.

Summary

The ListBox control in VB.NET is a useful tool for displaying a list of items for users to choose from. It can be customized to allow for the selection of one or multiple items, and items can be added to it programmatically using the Items.Add method.

Published on: