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(...) 值出现错误。

提前致谢,

4

2 回答 2

1

分配时,您正在寻址单元格[Col,Row],这是正确的。在您的控制回路 ( ShowMessage) 中,您已切换到寻址 [Row, Col],这是不正确的。

于 2011-05-02T21:21:38.120 回答
0

您在代码中混合了 row/col 和 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;
于 2011-05-02T18:53:45.827 回答