ListBox Control


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
Here List1 is the ListBox name.

Output:

Adding items in 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

Output:

Program to count the items in a listbox



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

Output: 

property to show index of 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