Use an event handler for multiple controls in C#

event handler

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.
    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;
    }
}

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 Example   Follow me on Twitter   RSS feed


This entry was posted in controls, Event and tagged , , , , , , , . Bookmark the permalink.

2 Responses to Use an event handler for multiple controls in C#

  1. Rod Stephens says:

    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?

  2. carla says:

    perfect! thanks a lot

Leave a Reply to carla Cancel reply

Your email address will not be published. Required fields are marked *