给你一个过程吧,我一直这样用的.
procedure TCommDm.InitComBox(ComBox: TComboBox; TbNm, FieldNm,IdxField,
sWhere: String; FirstFlag: Boolean);
var
sSql: String ;
begin
if sWhere = '' then
sSql := 'select '+FieldNm+' as FindVal from '+ TbNm + ' order by '+ IdxField
else
sSql := 'select '+FieldNm+' as FindVal from '+ TbNm + ' where '+ sWhere+ ' order by '+ IdxField ;
if CommonExecsql(CommQry,sSql) then begin
ComBox.Clear;
CommQry.First ;
while not CommQry.eof do begin
ComBox.Items.Add(CommQry.fieldbyname('FindVal').asstring);
CommQry.Next ;
end;
if FirstFlag and (ComBox.Items.Count > 0) then
ComBox.ItemIndex := 0 ;
CommQry.Close;
end;
end;
如果复杂点,几combobox中记录的不是数据表中的PK,而是可以重复的内容,那就要用一个
结构体来记录它们的相互关系了,就这样;
type
TDataRecd = Record
Index : Integer;
Value : String;
end;
DataRecd = array of TDataRecd;
procedure TCommDm.InitComBox(ComBox: TComboBox; Var LinkArr: DataLink; Const TbNm,
FieldNm,FieldID:String;sWhileSort:String=''; FirstFlag: Boolean=True);
var
sSql: String ;
iLoop: Word;
begin
if sWhileSort = '' then
sSql := 'select '+FieldNm+' As FindNm, '+FieldID+ ' as FindID from '+ TbNm + ' order by '+ FieldID
else
sSql := 'select '+FieldNm+' As FindNm, '+FieldID+ ' as FindID from '+ TbNm + ' where '+ sWhileSort + ' order by '+ FieldID ;
if CommonExecsql(CommQry,sSql) then begin
ComBox.Clear;
CommQry.First ;
SetLengTh(LinkArr,CommQry.RecordCount);
for iLoop:= 0 to CommQry.RecordCount -1 do begin
sSql := CommQry.fieldbyname('FindNm').AsString ;
ComBox.Items.Add(sSql);
LinkArr[iLoop]:= CommQry.Fieldbyname('FindID').AsInteger ;
CommQry.Next;
end;
if FirstFlag and (ComBox.Items.Count > 0) then
ComBox.ItemIndex := 0 ;
end;
end;