Title: Auto-search in ComboBox or ListBox
Question: 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.