Auto-search in ComboBox or ListBox (Views: 102)


How to realise automatic search feature in ComboBox?


For including this functionality we shall just handle KeyPress event of ListBox or ComboBox.
Below is demonstartion of this realisation:

1. Add string variable to your form:

  TForm = class(TForm)
    {....... }
    FSearchStr: string;

2. Add initialisation of this string variable in Form's OnCreate event:

FSearchStr := '';

3. Type the following code in OnKeyPress event of ListBox or ComboBox:

procedure TForm1.ListBox1KeyPress(Sender: TObject; var Key: Char);
  i: Integer;
  case Key of
        // Escape key, clear search string
        FSearchStr := EmptyStr;
      end; { Case Esc }
        // backspace, erase last key from search string
        if Length(FSearchStr) > 0 then
          Delete(FSearchStr, Length(FSearchStr), 1);
      end; { Case backspace }
    FSearchStr := FSearchStr + Key;
  end; { Case }
  if Length(FSearchStr) > 0 then
    if Sender is TListbox then
      i := SendMessage(TListbox(Sender).handle, LB_FINDSTRING,
        TListbox(Sender).ItemIndex, longint(@FSearchStr[1]));
      if i <> LB_ERR then
        TListbox(Sender).ItemIndex := i;
    else if Sender is TCombobox then
      i := SendMessage(TCombobox(Sender).handle, CB_FINDSTRING,
        TCombobox(Sender).ItemIndex, longint(@FSearchStr[1]));
      if i <> LB_ERR then
        TCombobox(Sender).ItemIndex := i;
  Key := #0;

Now you'll see how it will work.

<< Back to main page