Access to components by means of a loop  

Send By: Q3 Team
Web : http://www.q3.nu
Email: dlib@q3.nu
Date: 22/12/99

Tip accessed 495 times

 


It would sometimes interest us to access the components through a For ...Next loop. For example, Button[i] .caption := ' helo'. There is who prefers to make it creating array of controls. This well, but it puts under an obligation to program everything. In this example, we will change the captions of 5 buttons with a loop.

Put 5 TButtons in your form, Button1 ...Button5
Put this code in the OnCLick the Button1:


 procedure TForm1.Button1Click(Sender: TObject);
 var
    i:integer;
 begin
   for i:=1 to 5 do
     TButton( FindComponent('Button'+IntToStr(i)) ).Caption:='Hola';
 end;




Another manner:


 procedure TForm1.Button1Click(Sender: TObject);
 var
    i:integer;
 begin
   for i:=1 to 5 do
     (FindComponent('Button'+IntToStr(i)) as TButton).Caption:='Hola';
 end;



If the components were in another form, for example in form2:


 procedure TForm1.Button1Click(Sender: TObject);
 var
    i:integer;
 begin
   for i:=1 to 5 do
     (Form2.FindComponent('Button'+IntToStr(i)) as TButton).Caption:='Hola';
 end;