0

我想在 Delphi 7 的运行时从表中创建组件(面板),但仅在字段值 > 0 时创建。
示例:
widht |p1|p2|p3|p4|p5|p6|p7|.. |像素|
1500 | 5 | 5 | 5 | 0 | 0 | 0 | 0 |..|0 | // 创建 3 个面板
2700 | 5 | 5 | 5 | 6 | 6 | 0 | 0 |..|0 | // 创建 5 个面板
....

 private
{ Private declarations }
pn : array of TPanel;
..................................

procedure TForm1.Button1Click(Sender: TObject);
var i: integer;
oldpn: TComponent;
begin
table1.SetKey;
table1.FindNearest([form2.Edit2.Text]);
i:= table1.FieldCount;
SetLength(pn, i);
for i:= 1 to i-1 do
 begin
  oldpn:= Findcomponent('pn'+inttostr(i));
  oldpn.Free;
  pn[i]:= TPanel.Create(form1);
  pn[i].Parent := form1;
  pn[i].Caption := 'Panel' + inttostr(i);
  pn[i].Name := 'pn'+inttostr(i);
  pn[i].Height := table1.Fields[i].Value ;
  pn[i].Width := 500;
  pn[i].Color:=clGreen;
  pn[1].Top := form1.ClientHeight - pn[1].Height;
  if (i > 1) then pn[i].Top := pn[i-1].Top - pn[i].Height;
  pn[i].OnClick := pnClick;
 end;
end;

此代码为我创建了面板,但适用于所有字段。我希望能够仅从值 > 0 的字段中声明“pn”数组...
我尝试过:
如果 table1.Fields[i].Value > 0 然后
开始
i:= table1.FieldCount....
但是它不起作用。任何想法?提前致谢!

4

1 回答 1

1

我将创建第二个“计数器”来跟踪您实际在数组中设置的元素数量。我将数组设置为最大可能长度(您现在拥有的 Table1.FieldCount)。然后,一旦你遍历了所有字段,将数组的长度设置为那个“计数器”值。

就像是:

procedure TForm1.btn1Click(Sender: TObject);
var i: integer;
oldpn: TComponent;
count: Integer; // this keeps count of the number of panels you'll be creating
begin
  tbl1.SetKey;
  tbl1.FindNearest([form2.Edit2.Text]);
  i := tbl1.FieldCount;
  SetLength(pn, i);
  count := 0; // initialise count to 0
  for i := 1 to i - 1 do
    if tbl1.fields[1].value > 0 then
    begin
      oldpn := Findcomponent('pn' + inttostr(count));
      oldpn.Free;
      pn[count] := TPanel.Create(form1);
      pn[count].Parent := form1;
      pn[count].Caption := 'Panel' + inttostr(count);
      pn[count].Name := 'pn' + inttostr(count);
      pn[count].Height := tbl1.fields[count].value;
      pn[count].Width := 500;
      pn[count].Color := clGreen;
      pn[0].Top := form1.ClientHeight - pn[0].Height;
      if (count > 0) then
        pn[count].Top := pn[count - 1].Top - pn[count].Height;
      pn[count].OnClick := pnClick;
      inc(count);
    end;

  SetLength(pn, count); // re-adjust length of array
end;

可能有更好的方法来实现它,但这似乎很简单。

另外,用你的线:

pn[1].Top := form1.ClientHeight - pn[1].Height;

您是否尝试将其设置到表单的底部?您最好将该行更改为(以及下一行)单个 if 语句,以防止每次循环执行时都执行它:

if (count = 0) then
  pn[0].Top := form1.ClientHeight - pn[0].Height;
else
  pn[count].Top := pn[count - 1].Top - pn[count].Height; 
于 2013-06-19T04:57:02.163 回答