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)
- {
-
- foreach(Control ctl in Controls)
- if (ctl is Button bt)
- bt.Click += ClickEvents;
- }
-
- private void ClickEvents(object sender, EventArgs e)
- {
-
- if (!(sender is Button bt)) return;
-
-
- switch(bt.Text)
- {
- case "button1":
- {
- new FormAnonymous1().Show();
-
- break;
- }
- case "button2":
- {
-
- break;
- }
- case "button3":
- {
-
- break;
- }
- case "button4":
- {
-
- break;
- }
- case "button5":
- {
-
- break;
- }
- case "button6":
- {
-
- break;
- }
- case "button7":
- {
-
- break;
- }
- case "button8":
- {
-
- break;
- }
- case "button9":
- {
-
- break;
- }
- case "button10":
- {
-
- break;
- }
- }
- }
-
-
- }
- }
Plus - Using Anonymous
Using anonymous is a bit different, but I designed the code more efficiently in the following sample:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
-
- namespace MultiplesButtonClick2SingleFunction
- {
- public partial class FormAnonymous1 : Form
- {
- public FormAnonymous1()
- =>
- InitializeComponent();
-
- private void Form1_Load(object sender, EventArgs e)
- {
- foreach (Control ctl in Controls)
-
- if (ctl is Button bt)
-
- bt.Click += (ss, ee) =>
-
- { ClickEvents(((Button)ss).Text); };
- }
-
-
-
-
-
- private void ClickEvents(string text)
- {
- switch( text)
- {
- case "button1":
- {
- new FormRegular1().Show();
-
- break;
- }
- case "button2":
- {
-
- break;
- }
- case "button3":
- {
-
- break;
- }
- case "button4":
- {
-
- break;
- }
- case "button5":
- {
-
- break;
- }
- case "button6":
- {
-
- break;
- }
- case "button7":
- {
-
- break;
- }
- case "button8":
- {
-
- break;
- }
- case "button9":
- {
-
- break;
- }
- case "button10":
- {
-
- break;
- }
- }
- }
- }
- }
PLUS 2 - MIX MULTIPLES TYPE CONTROLS
In this sample, the Click event is trapped together.
Conclusion
Putting all click events in a single place is good way to improve the programming.
Happy coding.