Delphi从许多编辑中读取

时间:2013-03-02 15:55:57

标签: delphi pascal

是否有可能改变这样的事情:

myfunction(1,1,strtoint(form1.a11.text));
myfunction(1,2,strtoint(form1.a12.text));
myfunction(1,3,strtoint(form1.a13.text));
myfunction(1,4,strtoint(form1.a14.text));
myfunction(1,5,strtoint(form1.a15.text));
myfunction(1,6,strtoint(form1.a16.text));
myfunction(1,7,strtoint(form1.a17.text));
myfunction(1,8,strtoint(form1.a18.text));
myfunction(1,9,strtoint(form1.a19.text));

这样的事情?:

   for i:=1 to 9 do
      myfunction(1,i,strtoint(form1.'a1'+i.text));

我知道这不起作用,但我想找到更快的方法。类似的东西

1 个答案:

答案 0 :(得分:7)

您可以使用FindComponent按名称查找组件。这预先假定组件由表单对象拥有。机会很高,这是一个有效的假设。

(form1.FindComponent('a1'+IntToStr(i)) as TEdit).Text

我个人不喜欢这种代码。我会创建一个编辑控件数组:

type
  TForm1 = class
  ....
  private
    FEditArr: array [1..9] of TEdit;
  ....

然后在构造函数中我将初始化数组:

FEditArr[1] := a11;
FEditArr[2] := a12;
....

这使得随后获得编辑控件的代码给定索引更清晰。

如果沿着这条路走下去,那么在运行时也可能更容易创建编辑控件,而不必在设计器中创建它们,然后在构造函数中编写该数组赋值代码。概括地说,它看起来像这样。

for i := 1 to 9 do
begin
  FEditArr[i] := TEdit.Create(Self);
  FEditArr[i].Parent := Self;
  FEditArr[i].Left := ...;
  FEditArr[i].Top := ...;
end;