I have the following function that updates the UpdatePanel content by adding/loading an ascx custom usercontrol 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");
phmaincontent.Controls.Clear();
phmaincontent.Controls.Add(ctrl);
upmaincontent.Update();
}
Masterpage UpdatePanel:
<asp:UpdatePanel ID="upmaincontent" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lbmsg" runat="server" Text=""></asp:Label>
<asp:ContentPlaceHolder ID="cphmaincontent" runat="server">
</asp:ContentPlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
I am calling NavigationTab_Click from my navigation control that is another custom ascx control, my ctrl Control object that is loading dynamically on each has button and label when I click the button it simply reassigns some text to the label.
and I have this following code on my masterpage just 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);
base.OnInit(e);
}
so far everything works good, after loading my ctrl object by calling NavigationTab_Click function I see my ctrl in the placeholder and has the button and the label but the issue is this if I click this button it should reassign the label to some text but instead the whole ctrl control content disappears, please help.
When you're adding controls dynamically you must ensure that it gets recreated on every postback. You also have to ensure that you assign the same ID as before, otherwise events will not be triggered correctly and values cannot be reloaded from ViewState. This must be done it Page_Load at the latest(better in Page_Init).
That's the reason why you should avoid dynamical controls whenever possible.
So you can add controls in event-handlers like you've done. But they must be recreated on the next Postback. So you need to store somewhere what(f.e. IDs) or how many controls are already created. That can be done for example in
ViewState
orSession
. Then you can assign appropriate IDs to the controls(for example with the index or ID suffixed).Here are some additional informations on this subject: