Looping through Controls in VB.NET

前端 未结 4 1632
南笙
南笙 2021-01-22 18:04

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,

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 18:58

    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
    

提交回复
热议问题