Dynamically loaded user controls with event handlers - Unregister

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 ( , ), , ? , , . . , , . ?

+5
5

, , .

, .

, windows forms, , .

, , .net.

+5

MSDN :

Control..::. ControlCollection..::.

:

!

Clear . Dispose .

+2

,

0

, , , , . , - , , , , - , . .

, , (, , , asp.net), (, , - ..).

UserControl uc = LoadControl("control.ascx") as UserControl;
SomeObject so=Session["SomeObject"] as SomeObject;
If(so!=null)
{
    so.SomeEvent += new SomeEventHandler(uc.SomeMethod);
}

, .

. .

0

, controls.Clear , , .

, Clear, , , Controls.

0

All Articles