[英]How to create and use custom control with UpdatePanel added to the page programmatically
我有簡單的網絡用戶控件(我在網絡中某處找到的代碼):
<%@ 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();
}
現在,我想將此控件添加到我的頁面中(以編程方式在OnLoadComplete事件中):
<%@ Reference Control="~/WebUserControl1.ascx" %>
WebUserControl1 myControl = (WebUserControl1)Page.LoadControl("~/WebUserControl1.ascx");
myControl.ID = "myControl_" + some_name;
parentControl.Controls.Add(myControl);
當然,我的頁面上有SriptManager,並且控件已正確添加。 我知道每次頁面加載時都必須重新創建以編程方式添加的控件。 不幸的是,這導致創建新控件,因此無法選中復選框-在選中它之后,將再次觸發(頁面的)OnLoadComplete,並創建新控件。 如果我忽略了,則什么也不顯示。 所以問題是-如何做到這一點?
您可以在單擊按鈕時添加該控件,並將添加的控件的數量保存在某些存儲中,例如Session
。 在Page_Init
您需要檢查該計數值並重新創建之前添加的每個控件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.