Author: Igor Siticov
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:
1 type2 TForm = class(TForm)
3 {....... }4 private5 FSearchStr: string;
6 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:
7 8 procedure TForm1.ListBox1KeyPress(Sender: TObject; var Key: Char);
9 var10 i: Integer;
11 begin12 case Key of13 #27:
14 begin15 // Escape key, clear search string16 FSearchStr := EmptyStr;
17 end; { Case Esc }18 #8:
19 begin20 // backspace, erase last key from search string21 if Length(FSearchStr) > 0 then22 Delete(FSearchStr, Length(FSearchStr), 1);
23 end; { Case backspace }24 else25 FSearchStr := FSearchStr + Key;
26 end; { Case }27 if Length(FSearchStr) > 0 then28 if Sender is TListbox then29 begin30 i := SendMessage(TListbox(Sender).handle, LB_FINDSTRING,
31 TListbox(Sender).ItemIndex, longint(@FSearchStr[1]));
32 if i <> LB_ERR then33 TListbox(Sender).ItemIndex := i;
34 end35 elseif Sender is TCombobox then36 begin37 i := SendMessage(TCombobox(Sender).handle, CB_FINDSTRING,
38 TCombobox(Sender).ItemIndex, longint(@FSearchStr[1]));
39 if i <> LB_ERR then40 TCombobox(Sender).ItemIndex := i;
41 end;
42 Key := #0;
43 end;
Now you'll see how it will work.