I know control arrays don't actually exist anymore, but I need something I can relate to my code. I'm making a shopping list game with a grid of 32 tiles that flip when clicked. They are actually PictureBoxes called pbxTile1 - pbxTile32. I sense you already know what I'm going to say.
A sample of my code:
Private Sub pbxTile1_Click(sender As Object, e As EventArgs) Handles pbxTile1.Click
If TileFlag(1) = 0 Then Exit Sub
My.Computer.Audio.Play(My.Resources.Tile_Flip, AudioPlayMode.Background) : Application.DoEvents()
Me.pbxTile1.BackgroundImageLayout = ImageLayout.Stretch
Me.pbxTile1.BackgroundImage = My.Resources.FLIP01 : Application.DoEvents() : System.Threading.Thread.Sleep(50)
Me.pbxTile1.BackgroundImage = My.Resources.FLIP02 : Application.DoEvents() : System.Threading.Thread.Sleep(50)
Me.pbxTile1.BackgroundImage = My.Resources.FLIP03 : Application.DoEvents() : System.Threading.Thread.Sleep(50)
Dim GroceryValue = TileItem(1)
Call Get_Grocery(GroceryValue)
Me.pbxTile1.BackgroundImageLayout = ImageLayout.None
Me.pbxTile1.BackgroundImage = My.Resources.ResourceManager.GetObject(GroceryResource) : Application.DoEvents()
You can see my problem - this is a fraction of the subroutine, which I need to recreate 32 times. But I'm sure one of you bright lads can come up with something to make it much less painful for me! I've seen tagging, and lists, and indexing - but not sure how to apply it, which is best, and need some examples please!
It's ok, I've found it! My word it works perfectly:
I didn't realise that Event Handlers can handle multiple Controls!
Instead of duplicating my code (32 times!) I just changed the Sub to:
So basically if any of the 32 boxes are clicked, it calls the same Sub. And to differentiate between each PictureBox (this is the bit I was REALLY stuck on) I used DirectCast:
I'm not sure if this is the most streamlined way, but it certainly works a treat, and saved me a bunch of code I didn't need!