Usercontrol custom content in UpdatePanel disappears when clickbackback button is clicked

I have the following function that updates the content of the UpdatePanel by adding / loading a custom ascx custom control in the placeholder that is in default.aspx:

 protected void NavigationTab_Click(string ascxpath)
                        Control ctrl = LoadControl(ascxpath);
                        //cphmaincontent is my asp ContenPlaceHoderId in masterpage
                        PlaceHolder phmaincontent = (PlaceHolder)cphmaincontent.FindControl("phmaincontent");


UpdatePanel Master Page:

<asp:UpdatePanel ID="upmaincontent" runat="server" UpdateMode="Conditional">
                        <asp:Label ID="lbmsg" runat="server" Text=""></asp:Label>
                        <asp:ContentPlaceHolder ID="cphmaincontent" runat="server">                       


I am calling NavigationTab_Click from my nav control which is another custom ascx control, my ctrl control which is dynamically loaded on each has a button and a label, when I click the button it just reassigns some text to the label.

and I have the following code on my main page to get the ascx control path:

protected override void OnInit(EventArgs e)
               //raising an event to set ascx path
                mainmenu.NavigatePath += new usercontrols.mainmenu.NavigationHandler(NavigationTab_Click);



so far everything works well, after loading my ctrl object by calling the NavigationTab_Click function, I see my ctrl in placeholder and has a button and a label, but the problem is this, if I click on that button, it should reassign the label to some text but instead this all ctrl control content disappears, please help.


source to share

1 answer

When you add controls dynamically, you have to make sure that it is recreated on every postback. You also need to make sure you assign the same ID as before, otherwise events will not fire correctly and values ​​cannot be reloaded from ViewState. This should be done at least by Page_Load (better in Page_Init).

This is the reason why you should avoid dynamic controls whenever possible.

This way you can add controls to the event handlers as you did. But they should be recreated in the next Postback. So you need to store something (fe ID) somewhere or how many controls have already been created. This can be done, for example, in ViewState

or Session

. Then you can assign appropriate IDs to controls (for example, with an indexed index or ID).

Here is some additional information on this subject:



All Articles