Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

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

So how do you write the records of a database (from a TADOTable component) into a String grid? (the record's fields are all strings)

I tried something like this but to no avail:

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;

Example of the output I'm trying to get on startup: (Row number column is not part of the db)
enter image description here

Thanks in advance for the help!
Kind Regards
PrimeBeat

question from:https://stackoverflow.com/questions/65829235/delphi-reading-the-records-of-a-database-into-a-string-grid

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're going through far too much work. You don't need the separate stringlist at all, and your code could be much simpler.

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...