4

For a user control with internal data structures that must be disposed, is the correct place to add that code to the Dispose method in the .designer.cs file, or is there an event or something we're meant to use instead?

Edit: This is a winforms user control.

3 Answers 3

5

If you're talking about WinForms I usually take one of two approaches to solve this problem.

Approach 1

Open the Form.Designer.cs file. Inside the generated dispose method I add a call to DisposeCore. I then go back to Form.cs and add a DisposeCore method that will now be called during dispose. I add all of my dispose logic into this method.

Editing the designer file is technically not supported. However I've found that this particular edit will not be washed away when the designer regenerates code.

Approach 2

Add a event handler to Form.Disposed and do my dispose logic in the handler. This is the preferable way because it's a supported operation and won't be affected by some designer generation you have yet to encounter.

2
  • Only InitializeComponent() is regenerated. Anything else in that designer.cs is good to go. (For VS2005, at least)
    – Ken
    Nov 7, 2009 at 2:11
  • 1
    Wouldn't moving it be simpler?
    – Jon Coombs
    Feb 26, 2014 at 14:35
1

Could you clarify what kind of controls? ASP.NET, WinForms?

In ASP.NET you could:

protected override void OnUnload(EventArgs e){
     base.OnUnload(e);
     //Unload here...
}
1

Or, you could cut and paste it over to the main .cs file. That code is not inside of "#region Component Designer generated code", so Studio won't miss it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.