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
 
 
 
 
 
TitleSelect an item from a ListBox or ComboBox with a given ItemData value
Description
KeywordsListBox, ComboBox, list, item, select
CategoriesControls
 
The example works with a ListBox or a ComboBox. Code shown is for a ListBox.

Loop through the control's items examining their values. Select the target item if it is found.

 
Private Sub optBook_Click(Index As Integer)
    SelectItemData List1, Index
End Sub

' Search a control's ItemData property for the
' indicated ID. If found select the item.
Public Sub SelectItemData(ctl As Control, Id As Integer)
Dim nCnt As Long

    If TypeName(ctl) = "ComboBox" Or TypeName(ctl) = _
        "ListBox" Then
        For nCnt = 0 To ctl.ListCount - 1
            If ctl.ItemData(nCnt) = Id Then
                ctl.ListIndex = nCnt
                Exit For
            End If
        Next
    End If
End Sub
 
Formatted by Neil Crosby

Joanne James adapted this example to work in Visual Basic for Applications with Access 2003.

 
Public Sub SelectItemData(ctl As Control, Id As Integer)
Dim nCnt As Long
 
    If TypeName(ctl) = "ComboBox" Or TypeName(ctl) = _
        "ListBox" Then
        For nCnt = 0 To ctl.ListCount - 1
            If ctl.ItemData(nCnt) = Id Then
                 ctl = ctl.ItemData(nCnt)
                'ctl.ListIndex = nCnt 'can't set ListIndex
                'ctl.Selected(nCnt + 1) = True 'this dont
                ' work although MS help indicates it should
                ' in run time
                'ctl.selectedItem = 2 'this property not
                ' supported
                'ctl.selectedIndex = nCnt  'this property
                ' not supported
                Exit For
            End If
        Next
   End If
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated