Loading Nested UserControls in ASP.NET

我的未来我决定 提交于 2019-12-01 01:59:43

When you add a user control from the code behind, you have to actually load the control. You can do this by doing something like this:

protected void Page_Load(object sender, EventArgs e)
{
    for(int i=0;i<5;i++)
    {
        InnerUserControl cuc = (InnerUserControl)this.Page.LoadControl("InnerUserControl.ascx");

        holder.Controls.Add(cuc);
    }
 }

Assuming they are in the same directory. If not, put the virtual path as the parameter to the LoadControl method. You don't need to have the register statement on the outer control when you do this. Also, I usually use an on the code front instead of a div tag. I'm not sure if this makes a difference, however. I would also recommend loading the control OnInit, as this will ensure all phases of the Lifecycle run for your user controls.

Good Luck!

Have you tried adding

<%@ Reference Control="InnerUserControl.ascx" %>

to OuterUserControl.ascx

I'd recommend a different approach. Instead of instantiating the control object in the code-behind and adding it to the controls collection (which I think you'd probably need LoadControl() to do properly and do it earlier than page_load to hook it into the page lifecycle), add the inner control declaratively in the OuterUserControl.

If you need to add the InnerUserControl 5 times (like the example) declare the InnerUseControl inside a repeater. That is bound to the list of id's.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="OuterUserControl.ascx.cs" Inherits="Proj.OuterUserControl" EnableViewState="false" %>
<%@ Register src="InnerUserControl.ascx" tagname="InnerUserControl" tagprefix="uc1" %>
       <asp:Repeater ID="Repeater1" runat="server" DataSourceID="src">
    <ItemTemplate>
      <uc1:InnerUserControl id="iuc" runat="server" ID='<%#Eval("ID")%>'/>
    </ItemTemplate>
    </asp:Repeater>

    <asp:ObjectDataSource ID="src" runat="server" SelectMethod="IDList" 
        TypeName="Web.Default"></asp:ObjectDataSource>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!