Slorthe
Slorthe

Reputation: 121

How to embed user control (ascx) from code behind C#?

Embedding user controls into html page is easy but what about embedding user controls dynamically from code behind c#? Any help/suggestions would be greatly appreciated.

Upvotes: 1

Views: 1884

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460148

Use LoadControl to load and create a control dynamically. Then you can add it to the page's control-collection.

UcType myControl = (UcType) LoadControl("UcType.ascx");
this.SomeContainerContainerControl.Controls.Add(myControl);

where UcType is the type of your UserControl and SomeContainerContainerControl is the control you want to add this uc like a Panel. If you want to add it on top of the page simply use this.Controls.Add(myControl).

You should add it in Page_Init or Page_Load (at the latest). You have to recreate it on every postback as every other dynamic control with the same ID as before (if any).

Upvotes: 2

Julian Cr
Julian Cr

Reputation: 66

You can use the LoadControl() method and load it into a content control

example:

protected void Page_Load(object sender, EventArgs e)
{
    controls_example exmp = LoadControl("controls/example.ascx") as controls_example;
    myContentPanel.Controls.Add(exmp);
}

Upvotes: 0

Related Questions