Two buttons one subroutine

solfinker

Well-known member
Joined
Aug 6, 2013
Messages
71
Programming Experience
Beginner
Hello!
Is there an easy way to handle two different button.clicks with the same subroutine? A Public Function?
I am using different skins on the same form and the buttons change also quite a lot.

Thank you for your help.
 
As JohnH says, you simply include all the events you want to handle in the Handles clause of your method. They can be the same event for multiple objects of the same type or different object types or even different events, as long as the signatures are compatible.

You can add events to the Handles clause manually or you can have the IDE do it for you. In your case, to handle the Click event of two Buttons, select both your Buttons in the IDE, either with Ctrl+Click or Shift+Drag, and then open the Properties window. Click the Events button at the top and then double-click the Click event. That will generate a single method to handle the Click event for both Buttons. If you wanted to use that existing method to handle another event, you can use the drop-down in the Properties window against that event to select the existing method.
 
If you do have specific code that you want to happen depending on which button was pressed, you can determine which button by the sender variable:
    Private Sub button_Click(sender As System.Object, e As System.EventArgs) Handles btnTest.Click, btnTest2.Click
        MsgBox("You pressed " & DirectCast(sender, Button).Name, MsgBoxStyle.Information, "Test Button")
    End Sub
 
Back
Top