ASP.NET Custom user control to add dynamically

后端 未结 1 1417
天涯浪人
天涯浪人 2020-11-27 07:35

I have hard time to modify a page that had a Custom User Control directly to the ASPX page and now require to have it dynamically loaded when needed only. The User Control d

相关标签:
1条回答
  • 2020-11-27 07:47

    What I have done is use the Page.LoadControl method in the Page_Init to add the custom user control to a place holder on the page.

    protected void Page_Init(object sender, EventArgs e)
    {
        //MyControl is the Custom User Control with a code behind file
        MyControl myControl = (MyControl)Page.LoadControl("~/MyControl.ascx");
    
        //UserControlHolder is a place holder on the aspx page
        // where I want to load the user control to
        UserControlHolder.Controls.Add(myControl);
    }
    

    This works fine for me.

    Here is the code for the dynamically loaded user control:

    MyControl.ascx.cs

    public partial class MyControl : System.Web.UI.UserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            LiteralControl lit = new LiteralControl("Test Literal Control");
            Page.Controls.Add(lit);
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            whatever.Visible = true;
    
            if (IsPostBack)
            {
                whatever.Visible = false;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题