Looping through Controls in VB.NET

前端 未结 4 1631
南笙
南笙 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:42

    Generating controls at design time via the Forms Designer only makes sense for layouts which benefit from the forms designer.

    In your case, you just have 64 uniform boxes in 8 rows of 8. Don’t use the Forms Designer for this, create the controls at runtime, and don’t give them names like pba1, just put them into an appropriate data structure (such as an 8x8 array):

    Private chessFields As PictureBox(8, 8)
    
    ' In Form_Load:
    For i = 0 To 7
        For j = 0 To 7
            chessFields(i, j) = New PictureBox
            ' Set size, position … then, finally,
            Controls.Add(chessFields(i, j))
        Next
    Next
    

    That way, you can access the fields in an orderly fashion without having to go via the Form.Controls collection.

提交回复
热议问题