The TListBox Delphi control displays a collection of items in a scrollable list.
Items can be selected by clicking on an item, the ItemIndex property gets or sets the index of the selected item.
Incremental Searching for a ListBoxImagine a list box with a huge number of (unsorted) items. Finding the one user wants to select might turn into a nightmare.
Let's provide the user with an option to immediately locate the item in the list box by adding incremental search functionality.
Drop a TEdit and a TListBox on a form. Leave the default names: "Edit1" and "ListBox1".
Handle the Edit1's OnChange event as:
The StrPCopy RTL function copies Edit1.Test string value into a null-terminated string variable "search".
procedure TListBoxSearchForm.Edit1Change(Sender: TObject) ; const indexStart = -1; var search : array[0..128] of Char; begin //make sure Length(Edit1.Text) <= 128 StrPCopy(search, Edit1.Text) ; ListBox1.ItemIndex := ListBox1.Perform(LB_SELECTSTRING, indexStart, LongInt(@search)) ; end;
The Perform method sends the specific LB_SELECTSTRING message directly to ListBox1.
LB_SELECTSTRING expects two parameters: the zero-based index of the item before the first item to be searched - "indexStart" constant in the above code; and a pointer to the null-terminated string that contains the prefix for which to search - "search" variable in the above code.
The LB_SELECTSTRING searches a list box for an item that begins with the characters in a specified string. If a matching item is found, the item is selected. If the search is unsuccessful, the current selection is not changed.
Note: LB_SELECTSTRING can *not* be used when Multiselect property for a list box is true.