I have a user control which is being loaded to the page dynamically after performing a postback within an UpdatePanel.
Then I’m performing another postback for saving, where I would like to access the user input for the controls within that user control (for example, a grid with a checkbox in every row).
A simplified example if this scenario would be something as follows:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div><asp:Button ID="ButtonAdd" runat="server" Text="Add User Control" OnClick="ButtonAdd_OnClick" /></div>
<div id="divContent" runat="server"></div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div><asp:Button ID="ButtonSave" runat="server" Text="Save" OnClick="ButtonSave_OnClick" /></div>
</ContentTemplate>
</asp:UpdatePanel>
And:
protected void ButtonAdd_OnClick(object sender, EventArgs e)
{
MyUserControl uc = Page.LoadControl("MyUserControl.ascx") as MyUserControl;
divContent.Controls.Add(uc);
}
protected void ButtonSave_OnClick(object sender, EventArgs e)
{
// Hopefully, get controls from within the user control's grid and save their input
}
The problem is that after the save button is clicked, the user control is gone. That’s understandable and I have no problem creating and adding it again – but I do want to access the user input and save it. How can I do that?
If you want to add controls
programaticallythen choosePage_Load(more preferred) or Page_Init event. You can solve your problem by adding control “statically” (design time) withvisible=false and later you may turn on its visibility.In case you want stick with current approach as in your post, you have to use a trick.