Microsoft KB Archive/161161

= HOWTO: Search a ListBox Control Quickly =

Article ID: 161161

Article Last Modified on 2/24/2005

-

APPLIES TO


 * Microsoft Visual Basic 6.0 Learning Edition
 * Microsoft Visual Basic 6.0 Professional Edition
 * Microsoft Visual Basic 6.0 Enterprise Edition
 * Microsoft Visual Basic 5.0 Control Creation Edition
 * Microsoft Visual Basic 5.0 Learning Edition
 * Microsoft Visual Basic 5.0 Professional Edition
 * Microsoft Visual Basic 5.0 Enterprise Edition

-



This article was previously published under Q161161



SUMMARY
A popular item in a user interface is to "link" a text box to a list box so the nearest match in the list box is selected when the user types text into the text box. This technique can be implemented using pure Visual Basic code, but the Windows API provides a quicker and easier way to do this.



MORE INFORMATION
The technique calls the Windows API SendMessage function using the LB_FINDSTRING message for a list box to locate a partial match for a string in the list box. SendMessage requires the following parameters:      SendMessage(hWnd, LB_FINDSTRING, wParam, lParam) where

hWnd   - is the hWnd of the list box. wParam - is a long that specifies the starting point for the search. Use -1 to search the whole list box. lParam - is a long pointer to the string to find.

Step-by-Step Example
 Start a new Standard EXE project. Form1 is added by default. Add a TextBox control (Text1) and a ListBox control (List1) to Form1.  Add the following code to the General Declarations section of Form1: Const LB_FINDSTRING = &H18F Private Declare Function SendMessage Lib "User32" _ Alias "SendMessageA" _ (ByVal hWnd As Long, _         ByVal wMsg As Integer, _          ByVal wParam As Integer, _          lParam As Any) As Long

Private Sub Form_Load List1.Clear List1.AddItem "Apples" List1.AddItem "Banana" List1.AddItem "Bread" List1.AddItem "Break" Text1.Text = "" End Sub

Private Sub Text1_Change List1.ListIndex = SendMessage(List1.hWnd, LB_FINDSTRING, -1, _           ByVal Text1.Text) End Sub

 Press the F5 key to run the program. Typing text into the text box selects the first item in the list box which matches the text in the text box.

