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
...
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.
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()
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With