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.
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 subclassButtonin 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 🙂