I have a form with a panel in which I dynamically load several 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 just do
this.Panel.Controls.Clear();
Does Clear () help get rid of events or should I do
foreach(Control control in this.Panel.Controls)
{
UserControl userControl = control as UserControl;
if(userControl != null)
{
userControl -= userControl_Event;
}
}
before I clear () the contents of the panel?
Basically, I'm looking for a way to dynamically load user controls and handle their events without creating a leak when I get rid of them.
Thank!
EDIT:
Page_Init ( , ), , ?
, , . . , , . ?