00 Votes

Delphi: Select components via their names

Tip by Delphian | 2012-07-14 at 13:07

In this tip, I will show you how you can access components by using their name. This procedure is especially useful whenever you want to change a property on many components that are in the best case also consecutive numbered.

Our choice is the function FindComponent and it is used as follows:

(FindComponent('label1') as TLabel).color := clgreen;

Here we set the color of "label1" to "clgreen". It is important that we always have the right type of component (here "TLabel") behind the "as", otherwise there will be an error message. Furthermore, we can simply specify a string with the name of the component behind FindComponent. If we want, we can also use variables.

Example

In this example, we want to arrange "label1" to "label10" each at a distance of 20 pixels from top to bottom:

procedure TForm1.Button1Click(Sender: TObject);
var
   i: integer;
begin
   for i := 1 to 10 do
   (FindComponent('label'+inttostr(i)) as TLabel).top := i*20;
end;

In our loop, we count "i" from 1 to 10 and select with this and FindComponent the labels "label1" to "label10". The property "top" of this so-selected labels, we set to "i * 20", therefore the first label is set to 20, the second to 40 and so on.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.