Serillan
Serillan

Reputation: 227

Delphi reading from many edits

Is there a possiblity to change something like this:

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));

to something like this?:

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

I know this doesn't work but I want to find the way how to do it faster. something simular

Upvotes: 1

Views: 162

Answers (1)

David Heffernan
David Heffernan

Reputation: 613311

You can use FindComponent to locate the component by name. This presupposes that the component is owned by the form object. Chances are high that that is a valid assumption.

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

Personally I don't like this sort of code. I would create an array of edit controls:

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

Then in the constructor I would initialise the array:

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

This makes the code that subsequently gets an edit control given an index much cleaner.

If you go down this route then it's likely to be easier to create the edit controls at runtime too rather than have to create them all in the designer, and then write that array assignment code in the constructor. In outline, it looks like this.

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

Upvotes: 7

Related Questions