Mirror

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


Problem/Question/Abstract:

How to realise automatic search feature in ComboBox?

Answer:

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:

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

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);
var
  i: Integer;
begin
  case Key of
    #27:
      begin
        // Escape key, clear search string
        FSearchStr := EmptyStr;
      end; { Case Esc }
    #8:
      begin
        // backspace, erase last key from search string
        if Length(FSearchStr) > 0 then
          Delete(FSearchStr, Length(FSearchStr), 1);
      end; { Case backspace }
  else
    FSearchStr := FSearchStr + Key;
  end; { Case }
  if Length(FSearchStr) > 0 then
    if Sender is TListbox then
    begin
      i := SendMessage(TListbox(Sender).handle, LB_FINDSTRING,
        TListbox(Sender).ItemIndex, longint(@FSearchStr[1]));
      if i <> LB_ERR then
        TListbox(Sender).ItemIndex := i;
    end
    else if Sender is TCombobox then
    begin
      i := SendMessage(TCombobox(Sender).handle, CB_FINDSTRING,
        TCombobox(Sender).ItemIndex, longint(@FSearchStr[1]));
      if i <> LB_ERR then
        TCombobox(Sender).ItemIndex := i;
    end;
  Key := #0;
end;

Now you'll see how it will work.

<< Back to main page