Svish
Svish

Reputation: 158071

Where to unsubscribe events in a WinForms UserControl

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...

Upvotes: 7

Views: 4109

Answers (3)

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()

Upvotes: 5

samjudson
samjudson

Reputation: 56853

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);

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545618

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.

Upvotes: 2

Related Questions