C#.NET: Setting multiple controls to use a shared event handler

2013-10-29

If you have multiple controls on a form that are using identical event handlers, you can reduce duplication in your code by having all the controls point to only one of the event handler functions.

Screenshot of demo form showing two buttons

For simplicity sake, let’s imagine you have two buttons on your form that both launch a MessageBox when you click on them. If you were to create the event handlers by double-clicking the buttons in Form Design mode, your code would look like this:

[csharp]
using System.Windows.Forms;

namespace DemoMultipleControlsOneHandler {

public partial class MainForm : Form {

public MainForm() {

InitializeComponent();
}

private void firstButton_Click( object sender, System.EventArgs e ) {

MessageBox.Show( "Clicked!" );
}

private void secondButton_Click( object sender, System.EventArgs e ) {

MessageBox.Show( "Clicked!" );
}
}
}
[/csharp]

Obviously this example is a bit pedantic, but the code duplication is still present. We can refactor this to have the two buttons share one event handler.

[csharp]
using System.Windows.Forms;

namespace DemoMultipleControlsOneHandler {

public partial class MainForm : Form {

public MainForm() {

InitializeComponent();
}

private void HandleClick( object sender, System.EventArgs e ) {

MessageBox.Show( "Clicked!" );
}
}
}
[/csharp]

When you double-click a form control (in Form Design mode), Visual Studio automatically creates an event handler for that control’s default event. It also takes the liberty of connecting the control’s event to the new event handler. Since you are creating your own event handler, you will need to do the linking yourself.

  1. From the Form Design view, select the control you want to link up.
  2. Open up the Properties panel
  3. Switch to Events view (the lightening bolt icon)
  4. Find the event you’re interested in (in this example, that would be Click)
  5. Click the dropdown next to the event and select your handler (in this example, only HandleClick should appear).

Screenshot of Visual Studio showing how to link a handler to an event.

Note that if your event handler does not show up, you may not have the correct method signature. Visual Studio filters your functions and only shows the functions that accept the correct parameters for that event. If you are unsure what the function signature should be, double click the control in Form Design mode and have Visual Studio create the handler for you (you can then rename that function to something more appropriate for a shared handler).

Sample Code on GitHub