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

Solution 1:

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;

Solution 2:

In such a case I move the generated Dispose method to the main file and extend it. Visual Studio respects this.

An other approach would be using a partial method (C# 3.0).

Solution 3:

I believe in this case the code-generator honors your code. It should be safe to put it in the codebehind.

Solution 4:

In VS 2005 (and 2008) you can update the Dispose method and it will not get removed when you edit the control from the designer.

Solution 5:

You can move it out from the .designer.cs file and into the main .cs file if you want. As has been said already, it won't be overwritten.