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 2 type3 TForm = class(TForm)
4 {....... }5 private6 FSearchStr: string;
7 end;
8 9 //2.Add initialisation of this string variable in Form's OnCreate event: 10 11 FSearchStr := '';
12 13 //3.Type the following code in OnKeyPress event of ListBox or ComboBox: 14 15 procedure TForm1.ListBox1KeyPress(Sender: TObject; var Key: Char);
16 var17 i: Integer;
18 begin19 case Key of20 #27:
21 begin22 // Escape key, clear search string23 FSearchStr := EmptyStr;
24 end; { Case Esc }25 #8:
26 begin27 // backspace, erase last key from search string28 if Length(FSearchStr) > 0 then29 Delete(FSearchStr, Length(FSearchStr), 1);
30 end; { Case backspace }31 else32 FSearchStr := FSearchStr + Key;
33 end; { Case }34 if Length(FSearchStr) > 0 then35 if Sender is TListbox then36 begin37 i := SendMessage(TListbox(Sender).handle, LB_FINDSTRING,
38 TListbox(Sender).ItemIndex, longint(@FSearchStr[1]));
39 if i <> LB_ERR then40 TListbox(Sender).ItemIndex := i;
41 end42 elseif Sender is TCombobox then43 begin44 i := SendMessage(TCombobox(Sender).handle, CB_FINDSTRING,
45 TCombobox(Sender).ItemIndex, longint(@FSearchStr[1]));
46 if i <> LB_ERR then47 TCombobox(Sender).ItemIndex := i;
48 end;
49 Key := #0;
50 end;
Now you'll see how it will work.