Lesson 6: Mastering ListBox and ComboBox in VB2022

Create Dynamic Interfaces with List-Based Controls

Key Takeaway

ListBoxes display multiple items for selection, while ComboBoxes conserve space by showing only the selected item until expanded. Mastering these controls enables you to create organized, user-friendly interfaces for data selection.

Welcome to Lesson 6 of our Visual Basic 2022 Tutorial! In this lesson, you'll learn how to effectively work with ListBox and ComboBox controls. These powerful components allow you to present lists of items to users and capture their selections efficiently.

Learning Objectives

  • Understand the properties and methods of ListBox and ComboBox
  • Add and remove items programmatically
  • Implement multiple selection in ListBoxes
  • Create auto-complete functionality in ComboBoxes
  • Handle user selections and events

List Controls Comparison

Item 1
Item 2
Item 3
Item 4
ListBox (Shows all items)
Selected Item
ComboBox (Collapsed)
Selected Item
Item 1
Item 2
Item 3
ComboBox (Expanded)

6.1 ListBox Control

The ListBox displays a scrollable list of items that users can select. You can configure it to allow single or multiple selections, making it ideal for presenting choices to users.

Key ListBox Properties

Property Description
Items Collection of items in the ListBox
SelectedIndex Index of the currently selected item
SelectedItem The currently selected item object
SelectionMode Determines selection behavior (None, One, MultiSimple, MultiExtended)
Sorted Whether items are automatically sorted alphabetically

6.1.1 Adding Items to a ListBox

To add items programmatically, use the Add() method of the Items collection:

AddItems.vb
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
    ' Add a single item
    MyListBox.Items.Add("Vivo")
    
    ' Add multiple items using an array
    Dim colors() As String = {"Red", "Green", "Blue"}
    MyListBox.Items.AddRange(colors)
    
    ' Add items using InputBox
    Dim newItem As String = InputBox("Enter item to add:")
    If Not String.IsNullOrEmpty(newItem) Then
        MyListBox.Items.Add(newItem)
    End If
End Sub

Output:

Adding items at design time
Figure 6.1: Adding items at design time
Runtime view of ListBox items
Figure 6.2: Runtime view of ListBox items

Design Tip

For static lists, add items at design time using the Properties window. For dynamic lists that change at runtime, add items programmatically.

6.1.2 Removing Items from a ListBox

Remove items using the Remove() or RemoveAt() methods:

RemoveItems.vb
Private Sub BtnRemove_Click(sender As Object, e As EventArgs) Handles BtnRemove.Click
    ' Remove by item text
    If MyListBox.Items.Contains("Vivo") Then
        MyListBox.Items.Remove("Vivo")
    End If
    
    ' Remove by index
    If MyListBox.Items.Count > 0 Then
        MyListBox.Items.RemoveAt(0)  ' Remove first item
    End If
    
    ' Clear all items
    If MessageBox.Show("Clear all items?", "Confirmation", 
                      MessageBoxButtons.YesNo) = DialogResult.Yes Then
        MyListBox.Items.Clear()
    End If
End Sub

6.1.3 Working with Multiple Selections

Set the SelectionMode property to enable multiple selections:

MultipleSelection.vb
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Set SelectionMode to MultiExtended
    MyListBox.SelectionMode = SelectionMode.MultiExtended
End Sub

Private Sub BtnShowSelected_Click(sender As Object, e As EventArgs) Handles BtnShowSelected.Click
    Dim selectedItems As New System.Text.StringBuilder()
    
    ' Loop through all selected items
    For Each item As Object In MyListBox.SelectedItems
        selectedItems.AppendLine(item.ToString())
    Next
    
    If selectedItems.Length > 0 Then
        MessageBox.Show("Selected items:" & Environment.NewLine & selectedItems.ToString(), 
                        "Selected Items")
    Else
        MessageBox.Show("No items selected", "Information")
    End If
End Sub

Output:

6.2 ComboBox Control

The ComboBox combines a text box with a drop-down list, conserving screen space while providing selection options.

Key ComboBox Properties

Property Description
DropDownStyle Determines display style (Simple, DropDown, DropDownList)
AutoCompleteSource Source for autocomplete functionality
AutoCompleteMode Autocomplete behavior (None, Suggest, Append)
MaxDropDownItems Maximum number of items to show in the drop-down

6.2.1 Adding Items to a ComboBox

Adding items to a ComboBox is similar to ListBox:

ComboBoxAdd.vb
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Add items at form load
    myCombo.Items.Add("VB2022")
    myCombo.Items.Add("VB2019")
    myCombo.Items.Add("VB6")
    
    ' Set default selection
    myCombo.SelectedIndex = 0
End Sub

Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
    Dim newItem = InputBox("Enter new item:")
    If Not String.IsNullOrEmpty(newItem) Then
        ' Add if not already present
        If Not myCombo.Items.Contains(newItem) Then
            myCombo.Items.Add(newItem)
        End If
    End If
End Sub
ComboBox at runtime
Figure 6.3: ComboBox default view
ComboBox expanded
Figure 6.4: Expanded ComboBox

6.2.2 Removing Items from a ComboBox

Remove items using similar methods to ListBox:

ComboBoxRemove.vb
Private Sub BtnRemove_Click(sender As Object, e As EventArgs) Handles BtnRemove.Click
    Dim itemToRemove = InputBox("Enter item to delete")
    
    If itemToRemove IsNot Nothing AndAlso myCombo.Items.Contains(itemToRemove) Then
        myCombo.Items.Remove(itemToRemove)
    Else
        MessageBox.Show("Item not found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If
End Sub

6.2.3 ComboBox with AutoComplete

Enhance user experience with autocomplete functionality:

ComboBoxAutoComplete.vb
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Configure autocomplete
    myCombo.AutoCompleteMode = AutoCompleteMode.SuggestAppend
    myCombo.AutoCompleteSource = AutoCompleteSource.ListItems
    
    ' Add country names
    Dim countries() As String = {"United States", "Canada", "Mexico", 
                          "Brazil", "Argentina", "Chile", "United Kingdom", 
                          "France", "Germany", "Italy", "Spain"}
    myCombo.Items.AddRange(countries)
    
    ' Set default selection
    myCombo.SelectedIndex = 0
End Sub

Output:

Lesson Summary

In this lesson, we covered essential techniques for working with ListBox and ComboBox controls in VB2022:

ListBox Features

Display multiple items, support single/multiple selection, and allow item management

ComboBox Advantages

Save space with drop-down lists, support auto-complete, and provide selection options

Item Management

Add items with Items.Add(), remove with Items.Remove(), and clear with Items.Clear()

Selection Handling

Use SelectedItem and SelectedIndex properties to get user selections

AutoComplete

Enhance ComboBoxes with auto-suggest functionality for better UX

These skills enable you to create intuitive interfaces for data selection. In the next lesson, we'll explore working with PictureBox controls.

Exercises

Practice what you've learned with these exercises:

Exercise 1: Language Selector

Create a form with a ComboBox containing 5 programming languages. When the user selects a language and clicks a button, display the selected language in a message box.

Exercise 2: Shopping Cart

Build a form with:

  • A ListBox of available products
  • A second ListBox for the shopping cart
  • "Add to Cart" and "Remove from Cart" buttons

Exercise 3: Dynamic ComboBox

Create a ComboBox that loads country names from a text file when the form loads. Implement auto-complete functionality.

Exercise 4: Multi-Selection Manager

Build a form with:

  • A ListBox with SelectionMode set to MultiExtended
  • Buttons to move selected items between two ListBoxes
  • A "Clear All" button

Next Lesson

Ready to work with images? Continue to Lesson 7: Working with PictureBox Controls.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More