I am creating a subclass of Button and would like to add custom functionality to some of its events such as OnClick. Which is the more desirable way to do it? Do I override OnClick:
protected override void OnClick(EventArgs e) { base.OnClick(e); doStuff(); }
or should I instead link up the OnClick event to an event handler defined in my Button subclass through the designer?
class ButtonSubclass { public ButtonSubclass() : base() { InitializeComponent(); } private void InitializeComponent() { this.Click += new System.EventHandler(this.ButtonSubclass_Click); } }
Edit: I added minor visual changes (that may pass as rudimentary skinning) but most of the changes are in event handlers that I don't want to re-implement (copy-paste) on every form that reuses it.
In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.
This event handler invokes a JavaScript code when a click action happens on an HTML element. E.g., when we click a button, a link is pushed, a checkbox checks or an image map is selected, it can trigger the onClick event handler. This event handler invokes a JavaScript code when a window or image finishes loading.
To respond to an event, you define an event handler method in the event receiver. This method must match the signature of the delegate for the event you are handling. In the event handler, you perform the actions that are required when the event is raised, such as collecting user input after the user clicks a button.
If you're genuinely specializing the button, it makes sense to override OnClick
. If you're only actually changing what happens when a button is clicked, I wouldn't subclass Button
in the first place - I'd just add event handlers.
EDIT: Just to give a bit more of an idea - if you want to add similar event handlers for multiple buttons, it's easy enough to write a utility method to do that, and call it from multiple places. It doesn't require actual subclassing. That's not to say subclass is definitely wrong in your case, of course - just giving you extra options :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With