Introduction
In this post, I will demonstrate how to use a single function to trap all clickable buttons.
Events in .NET are very different from old events like Visual Basic 6.0, if you remember.
When I first migrated to OOP C#, I was very excited to use this feature to trap all buttons in one click.
THIS IS THE FORM SAMPLE
We have 10 buttons on it:

Here is the complete code:
- using System;
- using System.Windows.Forms;
- namespace MultiplesButtonClick2SingleFunction
- {
- public partial class FormRegular1 : Form
- {
- public FormRegular1()
- =>
- InitializeComponent();
- private void Form1_Load(object sender, EventArgs e)
- {
- // Read all controls in the form
- foreach(Control ctl in Controls)
- if (ctl is Button bt) // Select only Button type
- bt.Click += ClickEvents; // Add the event
- }
- private void ClickEvents(object sender, EventArgs e)
- {
- // Check if is a Button and init bt variable
- if (!(sender is Button bt)) return;
- // Check by the text caption of the button
- switch(bt.Text)
- {
- case "button1":
- {
- new FormAnonymous1().Show();
- // Do something
- break;
- }
- case "button2":
- {
- // Do something
- break;
- }
- case "button3":
- {
- // Do something
- break;
- }
- case "button4":
- {
- // Do something
- break;
- }
- case "button5":
- {
- // Do something
- break;
- }
- case "button6":
- {
- // Do something
- break;
- }
- case "button7":
- {
- // Do something
- break;
- }
- case "button8":
- {
- // Do something
- break;
- }
- case "button9":
- {
- // Do something
- break;
- }
- case "button10":
- {
- // Do something
- break;
- }
- }
- }
- }
- }
Plus - Using Anonymous
Using anonymous is a bit different, but I designed the code more efficiently in the following sample:

Sourav Kumar DasPosted Nov 3, 2019, 10:40 PM
Nice useful Article Sir.