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>
开发者_Python百科 <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 programatically
then choose Page_Load
(more preferred) or Page_Init event. You can solve your problem by adding control "statically" (design time
) with visible=fals
e 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.
MyUserControl uc;
protected void Page_Load()
{
if(ViewState["isAdd"]!=null)
{
AddControl();
}
}
void AddControl()
{
uc = Page.LoadControl("MyUserControl.ascx") as MyUserControl;
divContent.Controls.Add(uc);
}
protected void ButtonAdd_OnClick(object sender, EventArgs e)
{
if(ViewState["isAdd"]==null)
AddControl();
ViewState["isAdd"]="yes";
}
To access the internal controls, you have to expose them with properties or use FindControl
.
Also, as you mentioned, you have add dynamic controls back to the page on each postback.
Dynamic Web Controls, Postbacks, and View State
精彩评论