Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET: How to destroy dynamically added User Control
    text
    copied!<p>I added user control to a PlaceHolder with an ID phCustomFields. When I want to remove the user control in phCustomFields, i call phCustomFields.Controls.Clear(). However, after doing this, my usercontrol's Page_Load method still gets hit (i verified this by putting a breakpoint in the user control.) Why is my user control's page_load method still being called? i thought the instance of my user control was removed and destroyed once i called the Clear() method.</p> <p><strong>Update</strong></p> <p>Here is some sample code that demonstrates my problem. By setting the breakpoint at the Page_Load method of HelloWorld.ascx and debugging Page.aspx, the debug process would stop at the Page_Load method in HelloWorld.ascx which is expected and fine by me. But when I click on "Remove HelloWorld.ascx" button to remove the user control and then click on "Do Nothing" button to cause a postback, the debug process STILL stops at HelloWorld.ascx's Page_Load method. However, this shouldn't happen because the Clear() method in phTest was called.</p> <p><strong>Page.aspx</strong></p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page.aspx.cs" Inherits="WebApplication1.Page" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;script runat="server"&gt; 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(); } &lt;/script&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt; &lt;head runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:Button Text="Does nothing" runat="server" /&gt; &lt;asp:Button Text="Remove HelloWorld.ascx" OnClick="Remove_OnClick" runat="server" /&gt; &lt;asp:PlaceHolder ID="phTest" Visible="false" runat="server"&gt; &lt;/asp:PlaceHolder&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>HelloWorld.ascx</strong></p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HelloWorld.ascx.cs" Inherits="WebApplication1.HelloWorld" %&gt; &lt;script runat="server"&gt; protected void Page_Load(object sender, EventArgs e) { int i = 0; } &lt;/script&gt; &lt;b&gt;Hello World&lt;/b&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload