tags:

views:

164

answers:

4

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 />"));
}
+1  A: 

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 ...
benophobia
What is the use of setting an ID for?
the ID uniquely identifies the control - has to be UNIQUE on the whole page.
marc_s
+1  A: 

The problem appears to be in the cast rather than the loop.

I don't see the requirement for the explicit cast in your case. You could simply do something like :

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

And that should work. However, if you needed to set some explicit properties exposed by the WebUserControlAdult class, then you would need to cast. In that case, you should cast to the usercontrol class type (as @benophobia has illustrated).

Cerebrus
A: 

If your WebUserControl is a databound control, you may want to consider using Repeater Controls.

Using a repeater control, you would only need to put your control into the ItemTemplate of the repeater, e.g.,

<asp:Repeater ID="bunchOfControls" runat="server">
    <HeaderTemplate>
        <ul>
    </HeaderTemplate>
    <ItemTemplate>
        <li>
            <namespace:WebUserControlAdult runat="server />
        </li>
    </ItemTemplate>
    <FooterTemplate>
        </ul>
    </FooterTemplate>
</asp:Repeater>
Jon Limjap
A: 

dealing with dynamic user controls can be a pain in the ass.

as a rule of thumb i follow, whenever you create a dynamic user control, then you must set it's ID so ASP.net can reallocate it on post back, and to keep the controls values after post back you should reload your user controls on Page_Init event.

hope this helps.