I use asp.net and c# in web forms.
Using Visual Studio it creates automatically Event Handlers Methods for my controls.
VS generate the Method name in this way idControl_event. I know I can give any name to Event Handlers Methods.
-
So I’m wondering what is your favorite approach at naming theme.
-
I would like to know if using Web Forms is possible to write Event Handlers Method in a separate class (not in code behind for a specific web page) and how to call theme from the Control.
Thanks for your time.
For event handler names, I generally use the format that Visual Studio generates by default: [idControl]_[eventName]. But that is very much a personal/team preference. I’ve seen similar discussions about this such as this one or this one. Regardless of how you choose to name the event handlers, I think the most important thing is to remain consistent.
As for having the event handlers outside of your code behind, I haven’t seen this done very often but it is possible. The easiest way would be to have a static method in the separate class with the common event handling logic. For example, here is how you could have standard logic for Page.Loaded in a separate class. I believe you’ll need to register the event handler via code – I don’t think you can do it in markup (aspx).
Then in the code-behind of the page that you want to use that common event handler:
As another option, you could use inheritance to help with code reuse. For example, you could have a base class that your Pages inherit from that has standard handlers. One benefit of this is that you can register event handlers in markup even if the method is declared in a base class so you don’t need to do anything in the code-behind of the ancestor page.