[英]delphi7 create component from table fields
我想在运行时在Delphi 7中从表中创建组件(面板),但是仅在字段值> 0时才创建。
例:
宽度| p1 | p2 | p3 | p4 | p5 | p6 | p7 | .. | px |
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 ....
但它不起作用。 任何想法? 提前致谢!
我将创建第二个“计数器”,以跟踪您在数组中实际设置的元素数。 我将数组设置为最大可能的长度(您现在的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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.