Let controls share event handlers in C#

[share event handlers]

Sometimes it would be useful to let controls share event handlers. Often a program has several controls that do almost the same thing. It would be nice if they could share the same event handler to increase code reuse, but they don’t do exactly the same thing. You can still share code as long as that event handler can tell which control raised it.

An event handler’s first parameter, which is the object that raised the event, is declared as object sender. Giving the parameter the object data type makes different kinds of event handlers more uniform, but it makes them unable to easily use the controls that raised them. Still, the sender parameter is the way an event handler can tell which object raised it.

There are several approaches you can take to figure out which control raised an event. For example, you can use a series of if statements like this:

if (sender == btnPink) ...

Another approach is to convert the sender into the type of control that it really is. For example, the following code converts the sender into a Button.

Button btn = sender as Button;

Now you can do whatever you like to the Button. Note that this only works if the sender really is a Button. You cannot use this technique to have a Button and PictureBox share the same event handler.

A particularly useful trick for telling the event handler what to do is to put extra information in the control’s Tag property. The event handler can convert the sender into the correct type of control (or even the more generic Control type) and then use the Tag property to figure out what to do.

This example displays three buttons with their Tag properties set to Pink, LightGreen, and LightBlue. When you click a button, the following code uses those values to set the form’s background color.

// Use the selected color for the form's background.
private void btnColor_Click(object sender, EventArgs e)
    // Get the sender as a button.
    Button btn = sender as Button;

    // Convert its Tag value into a color.
    this.BackColor = Color.FromName(btn.Tag.ToString());

The code converts the sender into a Button. It then gets its Tag property, converts it into a string (Tag itself is an object), and passes it to Color.FromName to convert the color’s name into an actual Color.

You can use a similar technique in many menu items. For example, if the Scale menu has commands such as x1, x2, x4, and x1/2, you can store the values 1, 2, 4, and 0.5 in the items’ Tag properties.

Download Example   Follow me on Twitter   RSS feed   Donate

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