Title: Use an event handler for multiple controls in C#
Suppose you have several controls with event handlers that perform similar complex tasks. There are two general approaches for minimizing duplicated code.
The first is to move the common code into a separate method and make all of the event handlers call that method. This method is simple and effective, but it still gives you several different event handlers that really don't do much.
Another approach is to make one event handler that can do the work for all of the controls. Then in the Form Designer, select the controls, click the Events button on the Properties window (the little lightning bolt), select the event, open the dropdown to the right, and select the event handler. Now all of the controls use the same event handler for the event.
When you take this approach, the event handler often needs to know which control actually raised the event. You can use the sender parameter to figure that out.
The following code handles Button Click events for the example program's three Buttons. It converts the sender parameter into the Button that raised the event and then uses the Button's Text property to see which Button was clicked.
// The user clicked one of the buttons.
private void btnChoice_Click(object sender, EventArgs e)
// Get the sender as a Button.
Button btn = sender as Button;
// Do something with the Button.
MessageBox.Show("You clicked Yes");
MessageBox.Show("You clicked No. You're so negative!");
MessageBox.Show("You clicked Maybe. A bit undecided?");
Instead of using the sender's Text property, you could use the control's Tag property. Or you could compare the sender to controls directly as in the following code:
if (sender == btnYes) ...
The technique of using a single event handler minimizes repeated code, but it doesn't make clear the fact that the code is being used by multiple controls. Add a comment before the event handler to make that obvious.
Download the example to experiment with it and to see additional details.