Control Array Examples Needed for Visual Studio 2013

143 Views Asked by At

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!

1

There are 1 best solutions below

1
Jayce On

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:

Private Sub pbxTile_Click(ByVal sender As Object, e As System.EventArgs) Handles pbxTile1.Click, pbxTile2.Click, pbxTile3.Click, pbxTile4.Click, pbxTile5.Click, pbxTile6.Click, _
    pbxTile7.Click, pbxTile8.Click, pbxTile9.Click, pbxTile10.Click, pbxTile11.Click, pbxTile12.Click, pbxTile13.Click, pbxTile14.Click, pbxTile15.Click, pbxTile16.Click, _
    pbxTile17.Click, pbxTile18.Click, pbxTile19.Click, pbxTile20.Click, pbxTile21.Click, pbxTile22.Click, pbxTile23.Click, pbxTile24.Click, pbxTile25.Click, pbxTile26.Click, _
    pbxTile27.Click, pbxTile28.Click, pbxTile29.Click, pbxTile30.Click, pbxTile31.Click, pbxTile32.Click

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:

For z = 1 To 32
        If DirectCast(sender, PictureBox).Name = "pbxTile" & z And TileFlag(z) = 0 Then Exit Sub
    Next

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!