VB3 How to Quickly Search a List Box

ID: Q119738

3.00 WINDOWS

The information in this article applies to:

SUMMARY

A popular item in a user interface is to "link" a text box to a list box so that as the user types text into the text box, the nearest match in the list box is selected. Although this technique can be implemented fairly easily using pure Visual Basic code, the Windows API provides a quick and easy way of doing this.

MORE INFORMATION

This technique uses the LB_FINDSTRING message for a list box to locate a partial match for a string in a list box. To do this, call the Windows API SendMessage function. The SendMessage function requires the following parameters to list the files:

   SendMessage (hWnd%,LB_FINDSTRING, wParam%, lparam)

where

   hWnd%     is the hWnd of the list box.
   wParam%   is an integer 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.

Example to Demonstrate Searching a List Box

1. Start a new project in Visual Basic and add a text box (Text1) and a

   list box (list1) to Form1.

2. Add the following code to the General declarations section of Form1:

  ' Enter the Declare statement on one single line:
   Declare Function SendMessage Lib "user" (ByVal hwnd As Integer,
      ByVal wMsg As Integer, ByVal wp As Integer, lp As Any) As Long
     Const WM_USER = &H400
   Const LB_FINDSTRING = (WM_USER + 16)

3. In the Form_Load method for the form, add a few items to the list box
   using the following code:

   Sub Form_Load()
       List1.Clear
       List1.AddItem "Apples"
       List1.AddItem "Banana"
       List1.AddItem "Bread"
       List1.AddItem "Break"
   End Sub

4. In the Change method of the text box, add the following code:

   Sub Text1_Change()
       ' The following code should be on one single line:
     List1.ListIndex = SendMessage(List1.hWnd, LB_FINDSTRING, -1, ByVal
     Cstr(Text1.Text))
   End Sub

When the code runs, typing text into the text box will select the first item in the list that matches the text in the text box.

KBCategory: KBSubCategory: APrgDataAcc Additional reference words: 3.00

Keywords          : kbcode
Version           : 3.00
Platform          : WINDOWS

Last Reviewed: May 21, 1998