vbnet
  1. vbnet-combobox-control

Working with Forms and Controls in VB.NET - ComboBox Control

The ComboBox control in VB.NET is a powerful tool for creating drop-down lists that allow users to select items from a list of options. It can be bound to a data source or populated manually with items.

Syntax

ComboBox1.Items.Add("Item 1")
ComboBox1.Items.Add("Item 2")
ComboBox1.SelectedIndex = 0

To manually add items to a ComboBox control, you can use the Add method of the Items property. You can also set the initial selected item using the SelectedIndex property.

Dim items As String() = {"Item 1", "Item 2", "Item 3"}
ComboBox1.Items.AddRange(items)

To add multiple items at once, you can use the AddRange method and pass in an array of items.

Example

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim items As String() = {"Apples", "Oranges", "Bananas", "Grapes"}
        ComboBox1.Items.AddRange(items)
        ComboBox1.SelectedIndex = 0
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MsgBox("You selected: " & ComboBox1.SelectedItem.ToString())
    End Sub
End Class

Output

When the ComboBox is clicked and an item is selected:

You selected: Apples

Explanation

In the above example, we have created a ComboBox control and added four items to it using the AddRange method. We then set the initial selected item using the SelectedIndex property. When the user clicks the button, a message box is displayed with the selected item.

Use

The ComboBox control can be used in a variety of scenarios, such as selecting items from a list, filtering search results, or choosing options from a list of settings. It can also be data-bound to a data source, allowing users to select items from a database query result set.

Important Points

  • The ComboBox control can be populated manually or bound to a data source.
  • The Add method is used to add a single item, while the AddRange method is used to add multiple items.
  • The SelectedIndex property is used to set the initial selected item.
  • The SelectedItem property is used to get the currently selected item.

Summary

In summary, the ComboBox control is a powerful tool for creating drop-down lists in VB.NET. It can be populated manually or bound to a data source and provides a flexible and intuitive user interface for selecting items from a list.

Published on: