Mike mik
Mike mik

Reputation: 91

Why runtime created TControl children not in Controls[]?

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?

Upvotes: 1

Views: 237

Answers (2)

Fabrizio
Fabrizio

Reputation: 8043

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:

Upvotes: 1

Mike mik
Mike mik

Reputation: 91

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

Upvotes: 1

Related Questions