I'm very new to coding and currently I am coding a VB.net Windows Form Hangman game. I have 26 letter buttons that when pressed I would like the text of them (A,B,C,Etc.) to be put into a Text box so the player knows what letter they have inputted and they can then submit their guess. However, so far the only way I have figured out how to detect when any of the buttons is pressed is by writing the code individually for each button which looks very messy and inefficient. I was wondering if it was possible to detect when any of the buttons is pressed (And know which one) without writing code for each individual button?
This is only for 4 of the buttons so I have to do this 22 more times for what I want to do and more for any additional buttons:
Current Code:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
TextBox2.Text = Button3.Text
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
TextBox2.Text = Button4.Text
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
TextBox2.Text = Button5.Text
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
TextBox2.Text = Button6.Text
End Sub`
This is the game when run. When any of the letter buttons are pressed I would like them to be detected. The text box on the right shows the button that is pressed:(https://hi.stack.imgur.com/92sDy.png)
I hope someone can help, thank you in advance, Georgitzu
CodePudding user response:
Here's the basic idea ...
' assign all button click events to the same routine
Private Sub buttonHandler(sender As Object, e As EventArgs) _ Handles Button1.Click, Button1.Click .... Button26.Click
' create a generic button object to handle the button clicked
Dim obtn as Button = CType(sender, Button)
' display the text
TextBox2.Text = obtn.Text
Hope this helps, Mike