使用TStringGrid中的数据记录

3

我已经在Pascal中创建了一个记录类型TTableData,用于存储从TStringGrid获取的信息以供后续使用:

TTableData = record
  header: String[25];   //the header of the column (row 0)
  value : String[25];   //the string value of the data
  number: Integer;      //the y-pos of the data in the table
end;

但是,每当我试图通过遍历TStringGrid并从单元格中获取值来初始化这些对象时,这些值就会变成('','',0)(除了一些单元格以外,它们的值似乎还可以)。

以下是我读取TStringGrid数据的过程:

procedure TfrmImportData.butDoneClick(Sender: TObject);
begin
  Halt;
end;

{ initialize records which are responsible
for storing all information in the table itself }
procedure TfrmImportData.initTableDataObjects();

var
  i, j: Integer;

begin
  SetLength(tableData, StringGrid1.ColCount, StringGrid1.RowCount);

  for j:= 0 to StringGrid1.RowCount-1 do begin
    for i:= 0 to StringGrid1.ColCount-1 do begin
      with tableData[i,j] do begin
        header := StringGrid1.Cells[i,0];
        value := StringGrid1.Cells[i,j];
        number := i;
      end;
    end;
  end;

  for i:= 0 to StringGrid1.RowCount - 1 do begin
    for j:=0 to StringGrid1.ColCount - 1 do begin
        ShowMessage(tableData[i,j].header+': '+tableData[i,j].value);
    end;
  end;
end;

我不太确定这里发生了什么。当我使用断点并缓慢遍历代码时,我可以看到数据最初被正确读入(通过将鼠标悬停在第二个for循环中的tableData [i,j]上以查看其当前值),但是当我尝试在循环本身中使用ShowMessage(...)时,该值就变得错误了。
提前感谢。

2
在第一个循环中,您使用 tableData[Col,Row],而在第二个循环中,您使用 tableData[Row,Col] - Jørn E. Angeltveit
正如其他人所说,您在两个循环中切换了列/行。只是作为一个提示:如果您将循环变量从i和j更改为r和c,其中r表示行,c表示列,您就不会出现混淆了。 :) - Ken White
2
@Ken White: 或者说,Bob帮助我们,"行"和"列",甚至是"列"。现在我们不再局限于每行69列和每个变量名6个字符,可以有相当具描述性的名称和可读代码。 - Мסž
2个回答

1

当你进行赋值操作时,需要使用cells [Col, Row]来指定单元格,这是正确的。但在你的控制循环(ShowMessage)中,你切换到了使用[Row, Col],这是错误的。


0

你的代码中混淆了行/列和i/j。

这可能是你想要做的:

procedure TfrmImportData.initTableDataObjects();
var
  i, j: Integer;

begin
  SetLength(tableData, StringGrid1.RowCount, StringGrid1.ColCount);

  for i:= 0 to StringGrid1.RowCount-1 do begin
    for j:= 0 to StringGrid1.ColCount-1 do begin
      with tableData[i,j] do begin
        header := StringGrid1.Cells[i,0];
        value := StringGrid1.Cells[i,j];
        number := i;
      end;
    end;
  end;

  for i:= 0 to StringGrid1.RowCount - 1 do begin
    for j:=0 to StringGrid1.ColCount - 1 do begin
        ShowMessage(tableData[i,j].header+': '+tableData[i,j].value);
    end;
  end;
end;

2
你混淆了行和列。在 StringGrid.Cells 中,第一个索引是列,第二个是行。确实非常令人困惑。 - kludg
@Serg:有点难以适应,但完全合乎逻辑。这是Windows图形函数用于绘制的相同系统(水平、垂直)。例如,LineTo(0, 0, 150, 100) 表示从水平位置0,垂直位置0到水平位置150,垂直位置100绘制一条线,或者在像素数组中,从0,0的列/行到150/100的列/行。 - Ken White

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接