databasedelphiadotstringgrid

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


Solution

  • 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;