creating a control at run time

A

Andy Fish

Hi,

I have a web user control (i.e. one which I've made in the designer by just
dropping some other controls on). It works if I place it on a web form but
not if I try to add it dynamically. I'm just doing this:

MyControl ctl = new MyControl();
parentControl.Controls.Add(ctl);

when I call Add, the user control's page load event fires, but the child
controls are all set to null. Even if I call EnsureChildControls, they are
still null afterwards. How do I get the child controls of my user control
initialised?

TIA

Andy
 
J

Joerg Jooss

Andy said:
Hi,

I have a web user control (i.e. one which I've made in the designer
by just dropping some other controls on). It works if I place it on a
web form but not if I try to add it dynamically. I'm just doing this:

MyControl ctl = new MyControl();
parentControl.Controls.Add(ctl);

when I call Add, the user control's page load event fires, but the
child controls are all set to null. Even if I call
EnsureChildControls, they are still null afterwards. How do I get the
child controls of my user control initialised?

In case of a user control, you have to load the *.ascx file:

Control userControl = LoadControl("MyControl.ascx");
parentControl.Controls.Add(userControl);

Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,153
Latest member
NamKaufman
Top