views:

23

answers:

2

When writing up a codebehind in Visual Studio for ASP.NET web forms applications, I often use the dropdowns at the top of the window to autogenerate page event handlers (e.g. Page_Load, Page_PreRender). I've noticed that sometimes Visual Studio likes to add numbers to these function names like "Page_Load1" or "Page_PreRender2".

Programatically speaking, this has no effect on the code. But stylistically, I find it a bit ugly. Is there any way to get rid of this behavior?

+2  A: 

VS will do this if the event handler already exists, but has been disconnected from the event.

You can reproduce this behavior as follows.

  • Create a form with only a button (leave the default name of Button1

  • Double-click it to create the event handler Button1_Click

What you may not realize is that in addition to the code-behind, there is also a file for the designer and the .resx. I'm not sure which one has what, and I am not at a PC with Visual Studio, but in one of those files, there is a bunch of code defining the button, including a line that starts with

Button1.Click += new EventHandler

or something along those lines.

At this point all is good.. NOW to disconnect the button from the event...

  • In the form designer, delete the button

At this point, the Button1_click event handler still exists in code behind but is not tied to an event (because the button whose event it was tied to has been deleted.)

  • Drag a new button onto the form (still named Button_1)

At this point, there is a new Button_1, but the event handler is still not tied to your original Button1_Click event. So if you double-click on the button, a new eventhandler will be created (Button1_Click1())

David Stratton
+1  A: 

I assume it would be happening because you've already got a method named Page_Load in the current scope: Visual Studio has to differentiate between your existing method and the new one somehow.

Note that if you remove an event handler, Visual Studio only deletes the method in the code-behind file if it's empty: if you've modified the code, then it won't delete it from the code-behind file.

Dean Harding