Author: Tomas Rutkauskas
I have some alpha sorted items in a combo box (style csDropDown). When the user
types in text, the combo box incrementally searches but it does not set the
itemindex property. Is there a way of making it do this?
Answer:
You could use the OnChange handler to perform a CB_FINDSTRING with the current edit
text, then set the itemindex to the found item. But that is disruptive to typing,
if the found item is not the one the user wants he has no way to change it, since
each change triggers OnChange, which again finds the item. So you have to invest
considerably more effort into this. Attach these handlers to the OnKeyPress and the
OnChange event of the combobox, that seems to work fairly well.
1 2 procedure TForm1.ComboBox1Change(Sender: TObject);
3 var4 oldpos: Integer;
5 item: Integer;
6 begin7 with sender as TComboBox do8 begin9 oldpos := selstart;
10 item := Perform(CB_FINDSTRING, -1, lparam(Pchar(text)));
11 if item >= 0 then12 begin13 onchange := nil;
14 text := items[item];
15 selstart := oldpos;
16 sellength := gettextlen - selstart;
17 onchange := combobox1change;
18 end;
19 end;
20 end;
21 22 procedure TForm1.ComboBox1KeyPress(Sender: TObject; var Key: Char);
23 var24 oldlen: Integer;
25 begin26 if key = #8 then27 with sender as TComboBox do28 begin29 oldlen := sellength;
30 if selstart > 0 then31 begin32 selstart := selstart - 1;
33 sellength := oldlen + 1;
34 end;
35 end;
36 end;
This works with Win2000, but on a Win98 machine, the ItemIndex is getting set
incorrectly after the first search. To make it work under both Win2000 and Win98,
you could do something like this:
37 38 procedure TMainForm.ComboBoxKeyDown(Sender: TObject; var Key: Word; Shift:
39 TShiftState);
40 var41 s: string;
42 begin43 if key = VK_RETURN then44 begin45 s := TComboBox(Sender).Text;
46 {The search doesn't work in Win 98 with DroppedDown set to true}47 TComboBox(Sender).DroppedDown := false;
48 TComboBox(Sender).Text := s;
49 end;
50 end;