Looping through Controls in VB.NET

前端 未结 4 1658
南笙
南笙 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 19:07

    Put all the pictureboxes in an 8x8 tableLayoutPanel (also useful for scaling etc). Then

        For Each pb As PictureBox In TableLayoutPanel1.Controls
            Dim col As Integer = TableLayoutPanel1.GetCellPosition(pb).Column
            Dim row As Integer = TableLayoutPanel1.GetCellPosition(pb).Row
            If col Mod 2 = 0 Xor row Mod 2 = 0 Then
                pb.BackColor = Color.Black
            Else
                pb.BackColor = Color.White
            End If
        Next
    

    Of course you could also use an array of the squares if you have that available.

    This will not affect the events (pba1.click etc).

提交回复
热议问题