1

In a VCL application I need to access all the TControl children of a TForm. Children are declared as private TControl variables and are created in runtime using

I have used the following code:

unit MainForm;

interface
uses
   Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, System.Classes;

type
   TForm1 = class(TForm)
      procedure FormCreate(Sender: TObject);

      private
         myControl: tControl;
   end;

implementation
procedure TForm1.FormCreate(Sender: TObject);
var 
   NumOfControls: integer;
begin

   myControl:= tControl.Create(self);

   NumOfControls:= ControlCount;

end;

but NumOfControls is zero.

Is this normal behavior or I am missing something? If yes, how can I access Controls created during runtime?

Fabrizio
  • 7,603
  • 6
  • 44
  • 104
Mike mik
  • 91
  • 9
  • 1
    This might be a case of [Controls](http://docwiki.embarcadero.com/Libraries/Rio/en/Vcl.Controls.TWinControl.Controls) vs. [Components](http://docwiki.embarcadero.com/Libraries/Rio/en/System.Classes.TComponent.Components). – nil May 23 '19 at 11:40
  • 3
    After creating your controls, assign Parent: `C := TControl.Create(Self); C.Parent := Self;` – Ondrej Kelle May 23 '19 at 11:53
  • 3
    There's fake code here. What is `Control[]`? This is why you should always provide a [mcve]. – David Heffernan May 23 '19 at 11:59
  • Sorry. Its a type error. Its Controls[i] – Mike mik May 23 '19 at 12:22
  • It's still there. You should fix the question. To be perfectly honest though, if you can't provide a [mcve] which demonstrates the issue then I don't really see the point of keeping this post. – David Heffernan May 23 '19 at 12:35

2 Answers2

1

Ondrej Kelle answer is correct.

After creating your controls, assign Parent: C := TControl.Create(Self); C.Parent := Self;

Create(Self); does not assign Parent parameter to be the creator by default.

Thanks for that

Mike mik
  • 91
  • 9
1

You're setting Self as owner of myControl and not as its parent.

If you need to make Self to be the parent of myControl, you will need to set its Parent property:

myControl.Parent := Self;

Owner and parent are two different things. Basically owner manages the life of its owned components and the parent manages aspects that are more related to control's appearance, check this for a full explanation.

Also check these properties:

Fabrizio
  • 7,603
  • 6
  • 44
  • 104