title: Dynamically loaded user control with Event Handlers - Unregister
body: <p>I have a form with a panel on which I dynamically load multiple user controls. I handle events for each of these controls.</p>
  
  <pre><code>UserControl userControl1 = LoadControl("control.ascx") as UserControl;
  userControl1.Event += new ControlEventHandler(userControl_Event);
  this.Panel.Controls.Add(userControl1);
  
  UserControl userControl2 = LoadControl("control.ascx") as UserControl;
  userControl2.Event += new ControlEventHandler(userControl_Event);
  this.Panel.Controls.Add(userControl2);
  
  ...
  </code></pre>
  
  <p>Now when I get rid of the controls on the Panel, I simply do a </p>
  
  <pre><code>this.Panel.Controls.Clear();
  </code></pre>
  
  <p>Does the Clear() function take care of getting rid of the events or should I be doing</p>
  
  <pre><code>foreach(Control control in this.Panel.Controls)
  {
      UserControl userControl = control as UserControl;
      if(userControl != null)
      {
          userControl -= userControl_Event;
      }
  }
  </code></pre>
  
  <p>before I Clear() the content of the Panel?</p>
  
  <p>Basically, i'm looking for a way to load user controls dynamically and handle their events without creating a leak when I get rid of them.</p>
  
  <p>Thanks!</p>
  
  <p><strong>EDIT:</strong>
  Because my controls are created in the Page_Init event of the page (each time, as they are loaded dynamically), is it correct to say that their lifespan cannot be longer than the page's lifespan?
  From what I understand, the control doesn't exist after a post back. A new one is created each time. Therefore, I shouldn't have to unregister the event because the object it doesn't even exist on the next page load. Is that correct?</p>