简体   繁体   中英

TStringList to TStringGrid

This is my first post and I am still learning a lot about Delphi and general programming. So please feel free to teach.

I am trying to populate a TStringList with column names from Access. Then display them in a TStringGrid. I am currently getting an "Array Type required" error. But I fear there may be more.

procedure TFormDB1DataMapping.FieldNamesToGrid();
var
  myFieldnames: TStringList;
  I: Integer;
begin
  if not Form1.ConnIn1.Connected then begin
    try
      //Set Connection Parameters and connect
      Form1.ConnIn1Parameters;
      Form1.ConnIn1.Connected:=True
    finally
    end;
  end;
  myFieldnames := TStringList.Create;
  Form1.ConnIn1.GetFieldNames('','',Form1.ComboBoxDB1TableName.Text,'',myFieldnames);
  StringGridDB1.RowCount := StringGridDB1.RowCount + 1;
  for I:= StringGridDB1.RowCount - 1 downto 1 do
    StringGridDB1.Rows[I] := StringGridDB1.Rows[I - 1];
  StringGridDB1.Cols[0][1] := myFieldnames.Text;
  myFieldnames.Free;
End;

图片

Working procedure with answer below

procedure TFormDB1DataMapping.FieldNamesToGrid();
var
  myFieldnames: TStringList;
  I: Integer;
begin
  if not Form1.ConnIn1.Connected then begin
    try
      //Set Connection Parameters and connect
      Form1.ConnIn1Parameters;
      Form1.ConnIn1.Connected:=True
    finally
    end;
  end;
  myFieldnames := TStringList.Create;
  Form1.ConnIn1.GetFieldNames('','',Form1.ComboBoxDB1TableName.Text,'',myFieldnames);
  StringGridDB1.RowCount := StringGridDB1.RowCount + 1;
  StringGridDB1.RowCount := myFieldnames.Count + 1;
  for I := 0 to myFieldnames.Count - 1 do
    StringGridDB1.Cells[0, I + 1] := myFieldnames[I];
  myFieldnames.Free;
End;

图片

Assuming you want the field names in the first column sparing the top row for the header, you can do that with the following code:

StringGrid1.RowCount := myFieldnames.Count + 1;
for I := 0 to myFieldnames.Count - 1 do
  StringGrid1.Cells[0, I + 1] := myFieldnames[I];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM