views:

445

answers:

4

Where would you unsubscribe events in a UserControl? I subscribe to it in the Load event, like I have done in forms. And in forms I would usually unsubscribe in the Closing event, but I can't find anything similar in the UserControl...

+2  A: 

Is it necessary to unsubscribe at all? Is a reference to the user control held after it has been unloaded? If not, you don’t need to worry about the event handlers because as soon as the user control is removed from memory, so are the event handlers. You don’t leak references that way.

Konrad Rudolph
So if UserControl is listening to Something, and UserControl goes out of scope, then the event handler disappears and the UserControl will be collected like it should. While if Something goes out of scope, it won't be collected until either UserControl unsubscribes or goes out of scope itself. Did I get that right?
Svish
@Svish: No. If UserControl is listening to Something, and UserControl goes out of scope, UserControl will **not** be collected, as Something still holds a reference to UserControl. I Something goes out of scope and UserControl does not hold a reference to it, Something will be collected.
dtb
So in other words, if Something will exist after the UserControl dies, I will have to unsubscribe for the UserControl to be collected?
Svish
@Svish: Yes. But usually a UserControl just listens to its child controls which are referenced only from the UserControl (i.e. if the UserControl goes out of scope so do the child controls), so the UserControl doesn't have to unsubscribe from its child controls.
dtb
+1  A: 

As others have said is there really a need to unsubscribe in your scenario?

If you really do need to unsubscribe however you do it exactly the reverse of subscribing:

UserControl1.Click -= new EventHandler(UserControl1_Click);
samjudson
But where would I do it?
Svish
+1  A: 

There are times when you would want to do this (for example, when using CAB).
For completeness, the answer to your question is:

protected override void OnCreateControl()
{
    base.OnCreateControl();
    if(!DesignMode) //only time this.ParentForm should be null
        this.ParentForm.FormClosing += ParentForm_FormClosing;
}

private void ParentForm_FormClosing(object sender, FormClosingEventArgs e)
{
    //Unregister events here
}

You could also override Dispose()

BlueRaja - Danny Pflughoeft