Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleKeep track of checked ListBox selections as the user selects and deselects them in Visual Basic 6
DescriptionThis example shows how to keep track of checked ListBox selections as the user selects and deselects them in Visual Basic 6.
KeywordsListBox, selection, track selection, Visual Basic 6
CategoriesControls, 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
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated