If you select several Controls at design-time in Visual Studio, and use the context-menu, or the F4 key, to bring up the Property Browser, then select 'Events:
You'll see the list of Events that all selected Controls share.
You can double-click one of those Events, and Visual Studio will create a "stub" of an EventHandler for you with the required signature (object sender, SomeKindOfEventArgs e).
Or, you could write the EventHandler in code, then select the Controls, then open the Property Browser, then choose the EventHandler you wrote to bind to the selected Controls.
You do this with Controls inside different Container Controls, like one Control on the Form "surface," another Control inside a Panel inside another Panel, etc.
Or, in your code, you can assign multiple Controls to use the same EventHandler: what if I want to record an action every time any Button in a Panel in a Form is clicked ? And, let's imagine I have five Buttons, button1~button5 in 'panel1:
private void Form1_Load(object sender, EventArgs e)
{
foreach (Button aButton in panel1.Controls.OfType<Button>())
{
aButton.MouseClick += AButtonOnMouseClick;
}
}
private void AButtonOnMouseClick(object sender, MouseEventArgs mouseEventArgs)
{
Button theButton = sender as Button;
switch (theButton.Name)
{
case "button1":
MessageBox.Show("button 1");
break;
case "button2":
case "button3":
MessageBox.Show("button 2, or 3");
break;
default:
MessageBox.Show("any button not 1,2,3");
break;
}
}
What if I wanted to use the same EventHandler for both the Buttons, and two Labels in 'panel1:
private void Form1_Load(object sender, EventArgs e)
{
foreach (Button aButton in panel1.Controls.OfType<Button>())
{
aButton.MouseClick += SomeControlOnMouseClick;
}
foreach (Label aLabel in panel1.Controls.OfType<Label>())
{
aLabel.MouseClick += SomeControlOnMouseClick;
}
}
private void SomeControlOnMouseClick(object sender, MouseEventArgs mouseEventArgs)
{
if (sender is Label) handleLabel(sender as Label);
if (sender is Button) handleButton(sender as Button);
}
private void handleLabel(Label theLabel)
{
MessageBox.Show("clicked on Label: " + theLabel.Name);
}
private void handleButton(Button theButton)
{
switch (theButton.Name)
{
case "button1":
MessageBox.Show("button 1");
break;
case "button2":
case "button3":
MessageBox.Show("button 2, or 3");
break;
default:
MessageBox.Show("any button not 1,2,3");
break;
}
}
Note there are any number of ways you could structure this kind of code: my preference would be to define one EventHandler for each Control Type that I wanted to share an EventHandler: I feel that created more maintainable code, as well as avoiding having to test for the 'Type of the Control in order to decide which code to execute.