Keep track of checked ListBox selections

Started by nandagopal, May 20, 2009, 07:04 PM

Previous topic - Next topic

nandagopal

       
Title   Keep track of checked ListBox selections as the user selects and deselects them in Visual Basic 6
Description   This example shows how to keep track of checked ListBox selections as the user selects and deselects them in Visual Basic 6.
Keywords   ListBox, selection, track selection, Visual Basic 6
Categories   Controls, Miscellany

If you have a very large list (not recommended), it can take the program a while to loop through the whole list to find the items that are selected. This example maintains a collection that lists the selected items at all times.

When the user checks or unchecks an item, the ListBox's ItemCheck event handler fires. It determines whether the item is in the selected items collection and adds or removes it appropriately.


Private m_CheckedItems As New Collection

' Add or remove the item from the selected list.
Private Sub lstChoices_ItemCheck(Item As Integer)
    If lstChoices.Selected(Item) Then
        ' Add it to the selected list.
        m_CheckedItems.Add lstChoices.List(Item), _
            lstChoices.List(Item)
    Else
        ' Remove it from the selected list.
        m_CheckedItems.Remove lstChoices.List(Item)
    End If

    lblNumber.Caption = m_CheckedItems.Count & " items " & _
        "selected"
End Sub


To list the selected items, the program simply loops through the collection, not the entire list in the ListBox.


Private Sub cmdShowChoices_Click()
Dim i As Integer

    Debug.Print "**********"
    For i = 1 To m_CheckedItems.Count
        Debug.Print m_CheckedItems(i)
    Next i
    Debug.Print "**********"
End Sub