简体   繁体   中英

dynamically load a user control in the aspx page

I have the following aspx page for eg: called choosemenu.aspx

      <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
     <title></title>
 </head>
 <body>
     <form id="form1" runat="server">
         <div>
         </div>
       <div id="renderhere" runat="server">render user control here </div>
     </form>
 </body>
 </html>

I have a list of ascx pages called

 english.ascx
 commerce.ascx
 maths.ascx

I have to dynamically load the ascx files in my aspx page depending on the querystring in the aspx page.

I have the following contents in my aspx page in page_load event.

   var control = (English)Page.LoadControl("/ascx/english.ascx");

How will I render the contents of the english.ascx page in the choosemenu.aspx that too in this tag

Also I have to pass some value in the ascx file. This is the static stuff.

   <Menu:MNU ID="english" runat="server" HiLiter="<%#h %>"></Menu:MNU>

Loading a control from the server side

protected void Page_Load(object sender, EventArgs e)
{
    Page.Controls.Add(Page.LoadControl("~/ascx/english.ascx")); //CHECK THE PATH 
}

Loading a control from the server side and rendering it into a div If you want to render it in a specific div you might write:

protected void Page_Load(object sender, EventArgs e)
{
    UserControl uc = (UserControl)Page.LoadControl("~/ascx/english.ascx");
    uc.MyParameter = 1;
    uc.Id = 2;
    uc.someMethodToInitialize();
    div1.Controls.Add(uc);
}

and in your aspx page:

<div id="div1" runat="server">

</div>

Loading a control from the server side initializing the control with parameters

If your control has a constructor with parameters , you have to use:

public English_Control(int MyParameter, int Id) { //code here.. }

In you aspx.cs file you can initialize with:

UserControl uc = (UserControl)Page.LoadControl(typeof(English_Control), new object[] {1, 2});
div1.Controls.Add(uc);

In order for the control's postback values to be available, you must load and reload it no later than PreInit. Here is the code you need to do that.

    protected override void OnPreInit(EventArgs e)
    {
        string controlToLoad = String.Empty;
        //logic to determine which control to load
        UserControl userControl = (UserControl)LoadControl(controlToLoad);
        renderhere.Controls.Add(userControl);
        base.OnPreInit(e);
    }

As per MSDN :

Pre-Init event used to "Create or re-create dynamic controls."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM