ASP.NET: How to add two Web User Controls in the same aspx page dynamically

asp.net

How can I add two Web User Controls in the same aspx page dynamically? When I try to do that I get the following error

Unable to cast object of type 'ASP.webusercontroladult_ascx' to type 'WebUserControl'.

I am able to add 1 Web User control dynamically as

for (int i = 0; i < 2; i++)
{
    Control uc = (WebUserControl)Page.LoadControl("WebUserControlAdult.ascx"); 
    Panel1.Controls.Add(uc);
    Panel1.Controls.Add(new LiteralControl(@"<br />"));
}

Best Answer

Have you tried setting an ID for the user control? ie

 Control uc = (WebUserControl)Page.LoadControl("WebUserControlAdult.ascx");
 uc.id = "Dyn" + i.tostring();
 Panel1.Controls.Add(uc);

Or is the UserControl being cast to the wrong type? Maybe

(WebUserControlAdult)Page.LoadControl ...
Related Topic