1

I've recently noticed that the Visual Studio designer (I'm guessing it's called that) has been removing some of my method handles. Is there a way to stop designer from doing this?

An example of what I mean is this: I've got a method for when my MainForm closes called MainForm_Closing - basically a "Would you like to save changes?" prompt. Buried in my Main.designed.cs is the line:

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_Closing);

within the section relating to my MainForm object.

But if I make any visual changes to my MainForm (dragging a control onto it, editing a label name, changing an image property, etc.) it seems that the part of Visual Studio that creates the designer wipes out my custom code.

I'm guessing that the designer is called to create the designer.cs at compile time (so that it can easily compile to IL), and therefore removes my custom handles as a matter of course.

BTW: I'm generating my custom handles are being created with the help of IntelliSense. For example I type:

this.FormClosing +=

and IntelliSense suggests the correct handle and says "press TAB to insert").

Any help understanding this (and stopping Visual Studio from removing my handles) would be much appreciated.

Jamie Taylor
  • 1,644
  • 1
  • 18
  • 42
  • You are adding code to designer.cs? – Tomas Voracek Jan 26 '12 at 15:22
  • Did you add the EventHandler in from the Properties Pane or directly in the *.designer.cs file? PSimilar question answered well. http://stackoverflow.com/questions/3786512/changing-autogenerated-code-in-a-c-sharp-windows-forms-application-project – Lloyd Jan 26 '12 at 15:22
  • Only handles for methods like FomrClosing and TreeView.MouseClick and such. I take it that I should be adding this code elsewhere? – Jamie Taylor Jan 26 '12 at 15:23
  • Yes add EventHandlers in the properties pane not directly in the designer file. – Lloyd Jan 26 '12 at 15:25

2 Answers2

8

As mentioned in the .Designer.cs file, you shouldn't modify the code within the Windows Form Designer generated code region, as it's auto-generated and overwritten by Visual Studio each time the form is modified.

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>

To add handlers to the events of your controls, use the Properties dialog: enter image description here

ken2k
  • 48,145
  • 10
  • 116
  • 176
2

You should not modify designer.cs, on top of file is even added comment that it is generated by a tool by the way. Everytime you make changes in designer the designer.cs is regenerated, so never put your custom code in there.

Your custom code should be in MainForm.cs or some partial class file. Never modify designer.cs files because your code will be lost next time you open designer.

Tomas Voracek
  • 5,886
  • 1
  • 25
  • 41