Chimaobi Sylvester Chimaobi Sylvester - 6 months ago 8
Vb.net Question

How do i add different button clicks in one event method? c#

I have the following code in vb.net and it work well.

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click, btn1.Click, btn2.Click, btn1.Click
MsgBox("Hello world")
End Sub


It seems not to be working in c#.
How do I implement this in c#?

Answer

In c# it should be like this:

public Form1()
{
    InitializeComponent();
    // You should first subscribe the same handler to each button's click event:
    btnAdd.Click += btnAdd_Click;
    btn1.Click += btnAdd_Click;
    btn2.Click += btnAdd_Click;
}

void btnAdd_Click(object sender, EventArgs e)
{
    MessageBox.Show("Hello world");
}
Comments