问题
I have simple web user control (the code I found somewhere in the web):
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs"
Inherits="ARP.DynamicsCRM2011.MagicWebForm.WebUserControl1" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox1_CheckedChanged"
Text="Checkbox" />
<asp:Button ID="Button1" runat="server" Text="Button" Visible="False" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
Button1.Visible = CheckBox1.Checked;
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
}
Now I want to add this control to my page (programmatically in OnLoadComplete event):
<%@ Reference Control="~/WebUserControl1.ascx" %>
WebUserControl1 myControl = (WebUserControl1)Page.LoadControl("~/WebUserControl1.ascx");
myControl.ID = "myControl_" + some_name;
parentControl.Controls.Add(myControl);
Of course I have SriptManager on the page and my control is added properly. I know that programmatically added controls must be recreated every time the page is loaded. Unfortunately this causes creating new control, so checking checkbox doesn't work - after checking it the OnLoadComplete (of the page) is fired again and new control is created. If I omit that then nothing is displayed. So the question is - how to do this?
回答1:
Dynamic control should be re-added to the control tree OnPreInit
, see documentation:
PreInit - Create or re-create dynamic controls.
ASP.NET Page Life Cycle Overview
回答2:
You can add that control on button click and save count of added controls in some storage like Session
. The in Page_Init
you need to check that count value and recreate each control you have add before.
来源:https://stackoverflow.com/questions/8241856/how-to-create-and-use-custom-control-with-updatepanel-added-to-the-page-programm