[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.