To expand on the idea presented in my post; VB.NET Quick Tip – How To Radio Button Hack, I will show how to group regular form button presses under the same event.
This is useful when you have several buttons preforming related functions, i.e. controls for a media player. Also, grouping in this manner helps when debugging or updating your code. Start a new project and save it. Using a media player for our example place three buttons on a your main form. Name these buttons btnPlay, btnStop and btnPause.
Public Class frmMain Private Sub btnPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPlay.Click End Sub Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click End Sub Private Sub btnPause_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPause.Click End Sub End Class
Just like in the last Quick Tip, reduce the code to a single event handling all three button presses:
Public Class frmMain Private Sub btnPlayer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _ btnPlay.Click, btnStop.Click, btnPause.Click End Sub End Class
Here we will select for a case of matching text rather than evaluating a Boolean state True/False. To do this we need to discover which object fired the event, or in the programming parlance, the sender. This information is provided by the statement; ByVal sender As System.Object. So sender is where we find the value that we want to evaluate in our Select Case statement. We will also use a string variable and a message box to display the results of our button press:
Private Sub btnPlayer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _ btnPlay.Click, btnStop.Click, btnPause.Click Dim selected As String Select Case sender.name Case "btnPlay" selected = "Play" Case "btnStop" selected = "Stop" Case "btnPause" selected = "Pause" End Select MsgBox(selected & " Button Was Pressed") End Sub
Save your program and run the debug. That’s it. To apply this to Context Menu Strips, go on to: VB.NET Quick Tip – How To, Form Button Hack”
Disclaimer: The code in this tutorial is not intended as a final product or by no means the only way this project can be coded. The presented code is for educational purposes only and no warranty is granted or implied. I/we are not responsible for any damages as a result of using this code. Use at your own risk.