我將用戶控件添加到ID爲phCustomFields的PlaceHolder。當我想刪除phCustomFields中的用戶控件時,我調用phCustomFields.Controls.Clear()。但是,這樣做後,我的用戶控件的Page_Load方法仍然被打(我通過在用戶控件中放置一個斷點來驗證這一點)。爲什麼我的用戶控件的page_load方法仍然被調用?我認爲一旦我調用Clear()方法,我的用戶控件實例就被刪除並銷燬。ASP.NET:如何銷燬動態添加的用戶控件
更新
下面是一個說明我的問題的一些示例代碼。通過在HelloWorld.ascx的Page_Load方法中設置斷點並調試Page.aspx,調試過程將停止在HelloWorld.ascx中的Page_Load方法中,這是我所期待和罰款的。但是當我點擊「Remove HelloWorld.ascx」按鈕來刪除用戶控件,然後點擊「Do Nothing」按鈕來導致回發時,調試過程STILL停在HelloWorld.ascx的Page_Load方法中。但是,這不應該發生,因爲phTest中的Clear()方法被調用。
Page.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page.aspx.cs" Inherits="WebApplication1.Page" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Control C = LoadControl("HelloWorld.ascx");
phTest.Controls.Add(C);
}
protected void Remove_OnClick(object sender, EventArgs e)
{
phTest.Controls.Clear();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="Does nothing" runat="server" />
<asp:Button Text="Remove HelloWorld.ascx" OnClick="Remove_OnClick" runat="server" />
<asp:PlaceHolder ID="phTest" Visible="false" runat="server">
</asp:PlaceHolder>
</div>
</form>
</body>
</html>
HelloWorld.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HelloWorld.ascx.cs" Inherits="WebApplication1.HelloWorld" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
int i = 0;
}
</script>
<b>Hello World</b>
你能告訴我們一些小代碼嗎? – AnthonyWJones 2009-11-03 21:21:06