Board index » delphi » help creating component instances at runtime

help creating component instances at runtime

Hi

I need to create component instances at runtime. I wrote the following
test code that failed.

Any help would be appreciated.

var
  Form1: TForm1;
  l: tlabel;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
l := tlabel.Create(form1);
l.visible := true;
l.color := clred;
l.caption := 'testing';
l.show;
end;

 

Re:help creating component instances at runtime


Add to your code (right after creating the label)
l.parent := form1;
Quote
Bing wrote:
> Hi

> I need to create component instances at runtime. I wrote the following
> test code that failed.

> Any help would be appreciated.

> var
>   Form1: TForm1;
>   l: tlabel;

> implementation

> {$R *.DFM}

> procedure TForm1.Button1Click(Sender: TObject);
> begin
> l := tlabel.Create(form1);
> l.visible := true;
> l.color := clred;
> l.caption := 'testing';
> l.show;
> end;

Re:help creating component instances at runtime


Bing,

You need to tell the Tlabel control what it's parent is. For example:

procedure TForm1.Button1Click(Sender: TObject);
begin
 l := tlabel.Create(Self);
 l.Parent:=Self;
 l.color := clred;
 l.caption := 'testing';
end;

BTW, it's a really bad coding practice to reference the form instance
variable (form1) from within the form's methods.  Instead of using
form1, use Self instead.  This is a good idea because depending on how
the form was created, the form1 variable may or may not be valid.

Gerald

Other Threads