VB6 Tutorial 40: The Listbox Control

By | 2018-04-27

This lesson shows you how to work with the ListBox control in Visual Basic 6.

The first thing that you may want to do with the ListBox control is to add items or elements to it. You have two options for that. You can either add items in design-time or in run-time.

Adding items in design time

You can add items to ListBox using the List property.

Setting properties of the listbox control from the properties window:

Adding items in run-time

You can add items to ListBox using the AddItem method.

Example

Private Sub Form_Load()
    List1.AddItem "England"
End Sub

List1 is the name of the listbox.

Deleting an item from ListBox

You can remove an item using the RemoveItem method.

Syntax

ListBox.RemoveItem n

n is the index of an item. The Index starts from 0, so the index of the second item is 1.

Example

This program will delete the 1st item from ListBox.

Private Sub Form_Load()
    List1.RemoveItem 0
End Sub

Deleting all items

The Clear method removes all items from the Listbox.

Example

Private Sub Form_Load()
    List1.Clear
End Sub

Number of items in the ListBox

The ListCount property counts items in a ListBox.

Example

Private Sub Form_Load()
    Form1.Show
    Print lstCountry.ListCount
End Sub

Index number of the recently added item

The NewIndex property gives the index number which is most recently added using the AddItem method.

Example

Private Sub Form_Load()
    Form1.Show
    lstCountry.AddItem "England"    
    lstCountry.AddItem "USA"    
    lstCountry.AddItem "Germany"
    Print lstCountry.NewIndex
End Sub

Output: 2

Index number of the currently highlighted item

Index number of the currently highlighted item can be obtained using the ListIndex property. The value of ListIndex is -1 if no item is highlighted.

Example

Private Sub cmdShow_Click()
    Print lstCountry.ListIndex
End Sub

Private Sub Form_Load()    
    lstCountry.AddItem "England"    
    lstCountry.AddItem "USA"    
    lstCountry.AddItem "Germany"
End Sub

The output is the index number of the currently highlighted item.

The List property

The particular item of the ListBox having index n can be obtained using the List(n) property.

Example

Private Sub Form_Load()
Form1.Show    
lstCountry.AddItem "England"    
lstCountry.AddItem "USA"    
lstCountry.AddItem "Germany"
    Print lstCountry.List(0)
End Sub

Output

England

Currently highlighted item

The text property of ListBox gives the currently highlighted item/string.

Example

Private Sub Command1_Click()
     Print lstCountry.Text
End Sub

Private Sub Form_Load()
     lstCountry.AddItem "England"
     lstCountry.AddItem "USA"
     lstCountry.AddItem "Germany"
End Sub

Output

Text property to show the currently highlighted item in listbox

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.