Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through Controls in VB.NET

Tags:

vb.net

I am creating a chess program. And it is composed of sixty four picture boxes with alternating black and white background colours.
I have named them pba1, pba2, pbb1, pbb2, pbc1 and so on.
Now, I want to loop through only the black ones, for example, I want to loop through only, pba1, pbb2, pbc3 and so on.
How do I create a loop for this in VB.NET?

I know of the way to loop through similarly named controls, but I am not able to adapt that method for my problem. Can you tell me a solution?

EDIT: In pba1, pb stands for picture box, and a1 stands for the square. Just in case, you wonder why such a name.

EDIT: Check out this answer

like image 689
Rohit Shinde Avatar asked Feb 10 '26 13:02

Rohit Shinde


1 Answers

Loop through the PictureBox's in your ControlCollection and test for BackColor. I used the Form's ControlCollection, if they are in some other type of container control use that.

For Each cntrl As Control In Me.Controls
    If TypeOf cntrl Is PictureBox Then
        If cntrl.BackColor = Color.Black Then
            'Do Something
        End If
    End If
Next

Base on the additional information that you gave in your answer, the reason your example is not working is that the Controls Name is a String and you are comparing it to the PictureBox Control not the Name of the Control.

You can try using the Tag Property instead of the Name of the Control, it will be cleaner and easier to read. I just put a 1 in the PictureBox's Tag Property for Black and a 0 for White.

Private Sub OriginalColour()               
    For Each cntrl As Control In Me.Controls
        Dim result As Integer
        If TypeOf cntrl Is PictureBox Then
            If Integer.TryParse(cntrl.Tag.ToString, result) Then
                If result = 1 Then
                    cntrl.BackColor = Color.Gray
                Else
                    cntrl.BackColor = Color.White
                End If
            End If

        End If
    Next
End Sub
like image 185
Mark Hall Avatar answered Feb 15 '26 05:02

Mark Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!