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
...
views:
445answers:
4Is 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.
Do you need to unsubscribe?
Check out this: http://stackoverflow.com/questions/345130/do-i-need-to-unsubscribe-from-manually-subscribed-to-events-in-asp-net
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);
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()