Multiple Events in a single method

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello everyone...

I have 4 buttons (Button_1, Button_2, etc...), and I want to call the same
method regardless of which button is being clicked.

Once I am in the event, how do I know which button was pressed? Or do I
have to call a separte method for each button? Or is there magic with
"Sender as system.object" ?

Thanks,

Forch
 
Forch said:
I have 4 buttons (Button_1, Button_2, etc...), and I want to call the same
method regardless of which button is being clicked.

Once I am in the event, how do I know which button was pressed? Or do I
have to call a separte method for each button? Or is there magic with
"Sender as system.object" ?

\\\
Private Sub Button_Click(...) Handles Button1.Click, Button2.Click
Dim SourceControl As Button = DirectCast(sender, Button)
SourceControl.Text = "I was clicked!"
End Sub
///
 
Yes, you have to use the Sender parameter:

Private Sub Button_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click, Button2.Click

If sender Is Button1 Then
Me.Text = "You clicked Button1"
ElseIf sender Is Button2 Then
Me.Text = "You clicked Button2"
End If

End Sub
--

Carlos J. Quintero

MZ-Tools 4.0: Productivity add-ins for Visual Studio .NET
You can code, design and document much faster.
http://www.mztools.com
 
Yep:

this.button1.Click += new System.EventHandler(this.button_Click);
this.button2.Click += new System.EventHandler(this.button_Click);

private void button_Click(object sender, System.EventArgs e)
{
if (sender == this.button1)
this.Text = "You clicked button 1";
else if (sender == this.button2)
this.Text = "You clicked button 2";

}

--

Carlos J. Quintero

MZ-Tools 4.0: Productivity add-ins for Visual Studio .NET
You can code, design and document much faster.
http://www.mztools.com
 
Back
Top