首页 > 解决方案 > TStringList 到 TStringGrid

问题描述

这是我的第一篇文章,我还在学习很多关于 Delphi 和通用编程的知识。所以请放心教。

我正在尝试使用 Access 中的列名填充 TStringList。然后在 TStringGrid 中显示它们。我目前收到“需要数组类型”错误。但我担心可能还有更多。

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;

图片

工作流程及答案如下

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;

图片

标签: delphi

解决方案


假设您希望第一列中的字段名称保留标题的顶行,您可以使用以下代码执行此操作:

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

推荐阅读