使用标题案例查询结果填充ComboBox

Reg*_*ing 0 delphi combobox tadoquery database-table access

with TdmBCElections.Create(Self) do
begin
  with dmBCElections, qryParties do
  begin
    SQL.Clear;
    if rgpParty.ItemIndex = 0 then
      SQL.Text := 'SELECT StrConv(P_Surname, 3), StrConv(P_Names, 3) ' +
      'FROM Parties WHERE P_Type = "HEAD"'
    else
      SQL.Text := 'SELECT StrConv(P_Surname, 3), StrConv(P_Names, 3) ' +
      'FROM Parties WHERE P_Type = "TEACHER"';
    Open;
    while not Eof do
    begin
      cmbDetails.Items.Add(qryParties['StrConv(P_Surname, 3)'] + ', ' +
        qryParties['StrConv(P_Names, 3)']);
      Next;
    end;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了以下错误消息:

qryPartiesError

当StrConv应用于它们时,如何调用表字段?

Rem*_*eau 6

您可以为字段分配别名:

with TdmBCElections.Create(Self) do
begin
  with dmBCElections, qryParties do
  begin
    if rgpParty.ItemIndex = 0 then
      SQL.Text := 'SELECT StrConv(P_Surname, 3) as ConvertedSurname, StrConv(P_Names, 3) as ConvertedNames ' +
      'FROM Parties WHERE P_Type = "HEAD"'
    else
      SQL.Text := 'SELECT StrConv(P_Surname, 3) as ConvertedSurname, StrConv(P_Names, 3) as ConvertedNames ' +
      'FROM Parties WHERE P_Type = "TEACHER"';
    Open;
    while not Eof do
    begin
      cmbDetails.Items.Add(qryParties['ConvertedSurname'] + ', ' +
        qryParties['ConvertedNames']);
      Next;
    end;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

否则,您可以使用字段索引而不是名称:

with TdmBCElections.Create(Self) do
begin
  with dmBCElections, qryParties do
  begin
    if rgpParty.ItemIndex = 0 then
      SQL.Text := 'SELECT StrConv(P_Surname, 3), StrConv(P_Names, 3) ' +
      'FROM Parties WHERE P_Type = "HEAD"'
    else
      SQL.Text := 'SELECT StrConv(P_Surname, 3), StrConv(P_Names, 3) ' +
      'FROM Parties WHERE P_Type = "TEACHER"';
    Open;
    while not Eof do
    begin
      cmbDetails.Items.Add(qryParties.Fields[0].AsString + ', ' + qryParties.Fields[1].AsString);
      Next;
    end;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,我建议您考虑使用参数化查询:

SQL.Text := 'SELECT ... FROM Parties WHERE P_Type = :PType';
if rgpParty.ItemIndex = 0 then
  Parameters.ParamByName('PType').Value := 'HEAD'
else
  Parameters.ParamByName('PType').Value := 'TEACHER';
Run Code Online (Sandbox Code Playgroud)

  • @ LuiP3rd:因为ADO的`TParameter`没有`AsString`属性,比如`TField`和`TParam`.我最初发布的代码是假设`TQuery`,而不是'TADOQuery`(看看当你提供不完整的细节时会发生什么?).我现在更新了`TADOQuery`的代码. (2认同)