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 copies of 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 one of 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. Repeat for the other controls. 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 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.Instead of using the sender's Text property, you could the control's Tag property or compare the sender to controls directly as in the following code:
private void btnChoice_Click(object sender, EventArgs e)
{
// Get the sender as a Button.
Button btn = sender as Button;
// Do something with the Button.
switch (btn.Text)
{
case "Yes":
MessageBox.Show("You clicked Yes");
break;
case "No":
MessageBox.Show("You clicked No. You're so negative!");
break;
case "Maybe":
MessageBox.Show("You clicked Maybe. A bit undecided?");
break;
}
}
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.


This post is terribly simple, yet not obvious, in my opinion. It helped me alot. Thanks.
Reply to this
Can you help me writing codes which handle Button Click events for four events.
Reply to this
The instructions in the post should let you make one event handler that's shared by all four buttons. If you want separate event handlers, just double-click each button in the Windows Forms Designer.
If you had something else in mind, can you provide more detail?
Reply to this
Download link is not correct
Reply to this
Sorry about that! I've fixed it.
Reply to this
perfect! thanks a lot
Reply to this