<jeffz:SwitchPartManager ID="SwitchPartManager1" runat="server"Default.aspx.cs
PlaceHolderUpdatePanelID="UpdatePanel1" />
<asp:Button ID="ButtonA" runat="server" Text="ControlA" OnClick="ButtonA_Click" />
<asp:Button ID="ButtonB" runat="server" Text="ControlB" OnClick="ButtonB_Click" />
<hr />
<asp:UpdatePanel ID="UpdatePanel1" runat="server"></asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager sm = ScriptManager.GetCurrent(this);
sm.RegisterAsyncPostBackControl(this.ButtonA);
sm.RegisterAsyncPostBackControl(this.ButtonB);
}
protected void ButtonA_Click(object sender, EventArgs e)
{
SwitchPartManager.GetCurrent(this).SwitchTo("ControlA");
}
protected void ButtonB_Click(object sender, EventArgs e)
{
SwitchPartManager.GetCurrent(this).SwitchTo("ControlB");
}
This is Control A.ControlA.ascx.cs
<asp:LinkButton ID="LinkButton1" runat="server"
OnClick="LinkButton1_Click">Switch To Control B</asp:LinkButton>
protected void LinkButton1_Click(object sender, EventArgs e)
{
SwitchPartManager.GetCurrent(this.Page).SwitchTo("ControlB");
}
This is Control B
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<%= DateTime.Now %>
<asp:Button ID="Button1" runat="server" Text="Refresh Time" />
</ContentTemplate>
</asp:UpdatePanel>
[PersistChildren(false)]
[ParseChildren(true)]
[NonVisualControl]
public class SwitchPartManager : Control
{
private const string HiddenElementName = "__PartType__";
private bool initialized = false;
private string partTypeToSave = null;
public static SwitchPartManager GetCurrent(Page page)
{
return page.Items[typeof(SwitchPartManager)] as SwitchPartManager;
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (this.Page.Items.Contains(typeof(SwitchPartManager)))
{
throw new InvalidOperationException("One SwitchPartManager per page.");
}
this.Page.Items[typeof(SwitchPartManager)] = this;
this.Page.InitComplete += new EventHandler(Page_InitComplete);
this.Page.PreRenderComplete += new EventHandler(Page_PreRenderComplete);
}
private void Page_InitComplete(object sender, EventArgs e)
{
this.initialized = true;
string partType = this.Page.Request.Params[SwitchPartManager.HiddenElementName];
if (partType != null)
{
this.SwitchTo(partType);
}
}
private void Page_PreRenderComplete(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(this.partTypeToSave))
{
ScriptManager.RegisterHiddenField(
this.Page, SwitchPartManager.HiddenElementName, this.partTypeToSave);
}
}
// 得到作为容器的UpdatePanel
private UpdatePanel PlaceHolderUpdatePanel
{
get
{
// ...
}
}
public void SwitchTo(string partType)
{
Control container = this.PlaceHolderUpdatePanel.ContentTemplateContainer;
container.Controls.Clear();
Control control = this.Page.LoadControl(partType + ".ascx");
control.ID = "JustToPreserveUniqueName";
container.Controls.Add(control);
this.partTypeToSave = partType;
}
}
本文出自 “赵��” 博客,转载请与作者联系!