Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 468
Svish Avatar asked Sep 01 '09 12:09

Svish


People also ask

How do I add an event in Winforms?

You need to add a handler to the event. Double-click the KeyPress event in the textbox's Properties window to make Visual Studio generate an event handler in the code file.


3 Answers

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

like image 101
BlueRaja - Danny Pflughoeft Avatar answered Nov 19 '22 09:11

BlueRaja - Danny Pflughoeft


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.

like image 35
Konrad Rudolph Avatar answered Nov 19 '22 09:11

Konrad Rudolph


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);
like image 39
samjudson Avatar answered Nov 19 '22 10:11

samjudson