How do I add Dispose functionality to a C# UserControl?

e-holder picture e-holder · Oct 3, 2008 · Viewed 51.4k times · Source

I have a class which implements UserControl. In .NET 2005, a Dispose method is automatically created in the MyClass.Designer.cs partial class file that looks like this:

  protected override void Dispose(bool disposing)
  {
     if (disposing && (components != null))
     {
        components.Dispose();
     }
     base.Dispose(disposing);
  }

If I want to add my own Dispose functionality, where would I put it? Since this file is generated, I don't want to add code here and risk it getting blown away.

Answer

Jacob Seleznev picture Jacob Seleznev · Dec 1, 2008

All Component classes implement a Disposed event. You can add an event handler for that event and clean up things in there.

For example, in your UserControl you could add following method:

private void OnDispose(object sender, EventArgs e)
{
    // do stuff on dispose
}

And in constructor (or in Load event handler) add the following line:

Disposed += OnDispose;