Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle multiple click events with same Sub

I'm making a game for my visual basic course. I have multiple picture boxes that when clicked will reveal a hidden image individually. The point of the game is to find the matching pictures (simple enough).

On the easiest level, I have 16 picture boxes. The number of picture boxes increases as the difficulty increases.

For each picture box, I currently have an event handler as follows (default created by visual studio):

Private Sub pictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pictureBox1.Click

Inside, I plan to use this to change the image in the picture box, as follows:

pictureBox1.Image = (My.Resources.picture_name)

I would like to know if there is a way to have one Sub handle ALL the button clicks, and change the appropriate picture box, instead of having 16 separate handlers. For example:

Private Sub pictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
     Handles pictureBox1.Click, pictureBox2.Click, pictureBox3.Click, ... pictureBox16.Click

And do the following:

' Change appropriate picture box

Here's what it looks like (for now):
enter image description here

like image 230
Gingerbeard Avatar asked Jan 15 '23 01:01

Gingerbeard


1 Answers

To find out which PictureBox was clicked you just have to look at the sender variable. Obviously you have to convert it from the Object type to the PictureBox type:

Dim ClickedBox As PictureBox

ClickedBox = CType(sender, PictureBox)
like image 180
ZippyV Avatar answered Jan 30 '23 02:01

ZippyV