Delphi coding hints and tips.

Referencing a component by its name

Have you ever had the need to reference a component by it's name? One way of doing this is using FindComponent, a method of the TComponent class. If I had ten TLabels name Label1, Label2, etc up to Label10 within a TPanel on a form and wished to set all their captions form within a loop, here's how I could do it using FindComponent:-

var
  i:integer;
  c:TComponent;
begin
for i:=1 to 10 do
  begin
  {find component of given name}
  c:=Panel1.FindComponent('Label'+IntToStr(i));
  {if found component of given name and it is of correct
   type, set it caption property}
  if (c<>nil) and (c is TLabel)
  then
    begin
    TLabel(c).Caption:=IntToStr(i);
    end;
  end;

When a component is created it's owner property is set to the control that owns it. The parent control will then add a reference to the new component in it's components array property.

Note, FindComponent will only look at child components of component it is called from, its not recursive and does not look in the child component components array.