dynamically changing an asp User Control ?

I

ilPostino

ok, so I have my asp.net application.

I want a single page which can load asp user controls and at runtime. How
can this be done? I don't want to drag the control onto the page because
then I can't change it ... or can I ?

thanks

C
 
P

Philip Rieck

You can use something like this:

this.Controls.Add( Page.LoadControl("MyControl.ascx"));

If you want to put it in a specific place, use a placeholder or panel
control:

In your .aspx:
<asp:placeHolder id="dynamicCtl" runat="server" />

in your .aspx.cs :

....
if( someFlag)
{
dynamicCtl.Controls.Add( Page.LoadControl("MyControl.ascx"));
}
else
{
dynamicCtl.Controls.Add( Page.LoadControl("MyOtherControl.ascx"));
}
....


Note that dynamically placing controls has some behavior changes you should
think about, especially the fact that the usercontrol's child controls
will not keep their state anymore.



-Philip
 
I

ilPostino

Thanks - nice and easy! :)

C

Philip Rieck said:
You can use something like this:

this.Controls.Add( Page.LoadControl("MyControl.ascx"));

If you want to put it in a specific place, use a placeholder or panel
control:

In your .aspx:
<asp:placeHolder id="dynamicCtl" runat="server" />

in your .aspx.cs :

...
if( someFlag)
{
dynamicCtl.Controls.Add( Page.LoadControl("MyControl.ascx"));
}
else
{
dynamicCtl.Controls.Add( Page.LoadControl("MyOtherControl.ascx"));
}
...


Note that dynamically placing controls has some behavior changes you should
think about, especially the fact that the usercontrol's child controls
will not keep their state anymore.



-Philip
 

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

Top