How to add Dispose functionality in C # UserControl?

I have a class that implements UserControl. In .NET 2005, the Dispose method is automatically created in a partial class of the MyClass.Designer.cs class, which 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 do not want to add code here and risk blowing it off.

+56
c # dispose user-controls
03 Oct '08 at 16:04
source share
8 answers

In this case, I move the generated Dispose method to the main file and expand it. Visual Studio respects this.

Another approach would be to use a partial method (C # 3.0).

+48
Oct 03 '08 at 16:12
source share

All Component classes implement the Disposed event. You can add an event handler for this event and clear things there.

+63
Dec 01 '08 at 4:03
source share

I believe that in this case, the code generator honors your code. This should be safe to put in code.

+7
Oct 03 '08 at 16:07
source share

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

+6
03 Oct '08 at 16:08
source share

You can move it from the .designer.cs file to the main .cs file if you want. As already mentioned, it will not be overwritten.

+2
Oct 03 '08 at 16:09
source share

You just need to overload the public void Dispose () method in the component class that inherits the user control.

make sure that you pass the call to the base method, and also perform your listing functionally, or you will violate the functionality if you did not complete it completely.

+2
Apr 22 '09 at 10:35
source share

I would think that the cleanest way would be for your control to subscribe to its own Disposed () event and do its cleanup there.

0
Jun 13 '17 at 5:35
source share

there is an Unloaded event for UserControl that you can use to clear,

-2
May 25 '12 at 14:48
source share



All Articles