我觉得其实先把数据库中相关字段的内容先都加载到Combobox1中最好,免得频繁读取数据
库。输入前几位时可自动定位到相应的条目。代码可参照下面的代码:
private
selectItem:boolean;
procedure TForm1.FormShow(Sender: TObject);
begin
selectitem:=true;
With Dataset1 do
begin
Close;
CommandText:='select distinct 相应字段 from 表 where 相应字段 like '''+Combobox1.Text+'%''';
Open;
Combobox1.items.Clear;
while not eof do
begin
Combobox1.items.add(fieldbyname(相应字段).asstring);
next;
end;
close;
end;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
var sinput, sselected : string;
i, j : integer;
begin
j := 0;
if not selectitem then
begin
selectitem := true;
exit;
end;
sinput := copy((Sender as Tcombobox).text, 1, (Sender as Tcombobox).SelStart);
for i := 0 to (Sender as Tcombobox).items.count - 1 do
if copy((Sender as Tcombobox).items, 1, length(sinput)) = sinput then
begin
if j = 0 then sselected := (Sender as Tcombobox).items;
j := j + 1;
end;
if j > 0 then (Sender as Tcombobox).Text := sselected
else (Sender as Tcombobox).Text := sinput;
(Sender as Tcombobox).SelStart := length(sinput);
(Sender as Tcombobox).SelLength := length((Sender as Tcombobox).text) - length(sinput);
end;
procedure TForm1.ComboBox1KeyPress(Sender: TObject
var Key: Char);
begin
if key=#8 then selectitem:=false
else if key=#13 then selectNext(ActiveControl,true,true)
else (Sender as TCombobox).droppedDown:=true;
end;
procedure TForm1.ComboBox1Exit(Sender: TObject);
begin
(Sender as TCombobox).DroppedDown:=false;
end;