I have a form with a panel on which I dynamically load multiple user controls. I handle events for each of these controls.
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);
...
Now when I get rid of the controls on the Panel, I simply do a
this.Panel.Controls.Clear();
Does the Clear() function take care of getting rid of the events or should I be doing
foreach(Control control in this.Panel.Controls)
{
UserControl userControl = control as UserControl;
if(userControl != null)
{
userControl -= userControl_Event;
}
}
before I Clear() the content of the Panel?
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.
Thanks!
EDIT: 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?