Listbox Quickfind

From HashVB
Jump to: navigation, search

When you have a lot of items in a listbox, it is very useful to provide the user with some method to search the listbox. In situations where the user will know the exact string for which they are searching, Windows has a handy little method to allow them to do this very very quickly (as they type).

Add a TextBox and a ListBox to a form. For the sake of argument, we will call them txtFind and lstNames respectively. The following code will find and select the string that the user types into the ListBox if the ListBox contains the string, otherwise it will deselect everything:

   Private Sub txtFind_Change()
       If SendMessage(lstNames(cmbShowWhat.ListIndex).hWnd, LB_SELECTSTRING, -1, ByVal CStr(txtFind.Text)) = LB_ERR Then
           lstNames(cmbShowWhat.ListIndex).ListIndex = -1
       End If
   End Sub

Simple as that :)