Delphi - 将数据库的记录读入字符串网格

Delphi - reading the records of a database into a string grid

那么如何将数据库的记录(从 TADOTable 组件)写入字符串网格? (记录的字段都是字符串)

我尝试过类似的方法但无济于事:

procedure TfrmPuntehou.WriteToList(tbl: TADOTable;grid:TStringGrid);
var
  iNewRowCount:integer;
  i,j,m: Integer;
  const
  separator = ',';
begin
  tempList:= TStringList.Create;
  try
    tbl.First;
    while not (tbl.Eof) do
    begin
      tempList.Add(tbl['Car Number']+separator+tbl['Racer Name']+separator+tbl['Licence']);
      tbl.Next;
    end;
        for j:= 1 to (tempList.Count - 1) do
      begin
      grid.Rows[j].Text := tempList.Strings[(J-1)] ;
      end;
  finally
   tempList.Free;
  end;

      //fill the row numbers
      for m := 1 to grid.rowcount do
      begin
      grid.Cells[0,m]:= IntToStr(m);
      end;
end;

我试图在启动时获得的输出示例:(行号列不是数据库的一部分)

在此先感谢您的帮助!
亲切的问候
PrimeBeat

您的工作量太大了。您根本不需要单独的字符串列表,您的代码可以简单得多。

var
  i, Row: Integer;
begin
  // Populate header row
  Grid.Cells[0, 0] := 'Row';
  Row := 0;

  for i := 0 to Tbl.FieldCount - 1 do
    Grid.Cells[i + 1, Row] := Tbl.Fields[i].FieldName; // The +1 skips the Row column
  Inc(Row);
  // Populate cells
  Tbl.First;
  while not Tbl.Eof do
  begin
    for i := 0 to Tbl.FieldCount - 1 do
    begin
      Grid.Cells[i, Row] := IntToStr(i);                // Populate Row number
      Grid.Cells[i + 1, Row] := Tbl.Fields[i].AsString; // Fill rest of row with table data
    end;
    Inc(Row);
    Tbl.Next;
  end;
end;

这是一个使用 TADOQuery 和 StringGrid 的例子:

procedure TForm1.Button1Click(Sender: TObject);
var
    I    : Integer;
    ARow : Integer;
begin
    ADOConnection1.Open('user', 'pass');
    ADOQuery1.SQL.Text := 'SELECT * FROM dbo.Person';
    ADOQuery1.Open;
    if ADOQuery1.Eof then begin
        ShowMessage('Data not found');
        Exit;
    end;
    SGrid.RowCount := 1;
    SGrid.ColCount := ADOQuery1.Fields.Count + 1;
    // Create titles of row 0
    for I := 0 to ADOQuery1.Fields.Count - 1 do
        SGrid.Cells[I + 1, 0] := ADOQuery1.Fields[I].DisplayName;
    // Populate the cells with data from result set
    ARow := 1;
    while not ADOQuery1.Eof do begin
        Inc(ARow);
        SGrid.RowCount := ARow + 1;
        SGrid.Cells[0, ARow] := ARow.ToString;
        for I := 0 to ADOQuery1.Fields.Count - 1 do
            SGrid.Cells[I + 1, ARow] := ADOQuery1.Fields[I].AsString;
        ADOQuery1.Next;
    end;
end;

感谢Ken White的回答,我成功解决了问题!

procedure TfrmPuntehou.WriteToList(tbl: TADOTable;grid:TStringGrid);
var
  Row: Integer;
begin

  tbl.Active:=True;

  Row := 1;

  // Populate cells
  Tbl.First;
  while not Tbl.Eof do
  begin
    grid.Cells[0,Row]:= IntToStr(Row);
    grid.Cells[1,Row]:= tbl.fields[0].AsString;
    grid.Cells[2,Row]:= tbl.fields[1].AsString;
    grid.Cells[3,Row]:= tbl.fields[2].AsString;
    Inc(Row);
    IncreaseRowCount(grid);
    Tbl.Next;
  end;
  tbl.Active:=false;
end;