Connect Multiple Events to Single Event in Windows Forms, C# & VB.NET

How to connect or add multiple controls to a single WinForms event handler in c# & vb.net - patterns, Simple tutorial, examples & best practices.
In today's article I will show you how you can connect or use one event to multiple controls in windows forms application using c#.net and VB.net. This article will demonstrate Use One Event Handler for Multiple Controls in WinForms (C# / VB.NET), Wire Multiple Events to a Single EventHandler in Windows Forms - C# & VB.NET, Handle Many Click Events with One Method in WinForms (C#.NET / VB.NET), Best Practices: Reuse a Single Event Handler for Multiple Controls in WinForms. 

You may also like the below topics.

Now for this article first we will create a new windows application and add a form. In this form we will add few label and button controls to demonstrate the example. 

Windows Forms

Now we will generate click event of button as shown in below code. In this code I have added code which I will attach to button 1 and button 2. As per object or button text I have captured the text value and displayed. 

C#.Net

public Form3()
{
    InitializeComponent();
    button1.Click += new System.EventHandler(button1_Click);
    button2.Click += new System.EventHandler(button1_Click);
}

private void button1_Click(object sender, EventArgs e)
{
    Button button = (Button)sender;
    lblButtonValue.Text = $"{button.Text}";
}
 

VB.Net

Public Sub New()
    InitializeComponent()
    AddHandler button1.Click, New System.EventHandler(AddressOf button1_Click)
    AddHandler button2.Click, New System.EventHandler(AddressOf button1_Click)
End Sub

Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim button As Button = CType(sender, Button)
    lblButtonValue.Text = $"{button.Text}"
End Sub
Now we have done run the code to check the output. 

Multiple event in windows forms

Post a Comment