Kaleo Brandt
Kaleo Brandt

Reputation: 357

How to Call an Object Based on a Variable in Visual Studio?

So I'm trying to write a MasterMind game, but I have a problem

I have 40 pictureboxes set up in 10 different rows, and I want to have one code handle all 10 rows, rather than copying and pasting the code and changing the names of the pictureboxes. I've been trying to use a variable to achieve this, but if it's possible, then I don't know the correct way to do it.
This is what I have right now:

 Dim X As Integer
 Dim Y As Integer
 Private Sub ButtonCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonCheck.Click
    If HighlightRow1 = True Then
        X = 1
        Y = 2
        Check1()
    ElseIf HighlightRow2 = True Then
        X = 4
        Y = 5
        Check1()
    ...
    EndIf
  End Sub
  Private Sub Check1()
      If PictureBox(X).Tag = "Red" //'Getting this error: Class 'System.Windows.Forms.PictureBox' cannot be indexed because it has no default property.

         blah blah blah
      ElseIf PictureBox(X).Tag = "Green" Then
         blah blah blah
      ...
      EndIf  

      If Picturebox(Y).Tag = "Red" Then
         blah blah blah
      ...
      End If 

Is there any way to do this? I'm new at programming, so I'm sorry if this is a very simple question.

Upvotes: 1

Views: 1460

Answers (1)

sajattack
sajattack

Reputation: 813

To check all pictureboxes, put all your pictureboxes into an array and use a for each loop to check them.

Private Sub Check1()
    Dim picBoxArr() As PictureBox = {PictureBox1, PictureBox2, PictureBox3, PictureBox4}
    For Each picBox in picBoxArr
        If picBox.Tag = "Red" Then
            'yada yada
        End If
    Next
End Sub

To check a specific picturebox, omit the for each loop and address the picturebox you want to check with an index. Note: indexes start at zero so picturebox1 would have an index of zero in this case.

Private Sub Check1()
    Dim picBoxArr() As PictureBox = {PictureBox1, PictureBox2, PictureBox3, PictureBox4}
    If picBoxArr(0).Tag = "Red" Then
            'yada yada
    End If
End Sub

You can read more about arrays here http://msdn.microsoft.com/en-us/library/wak0wfyt.aspx

Upvotes: 1

Related Questions