循环遍历 VB.NET 中的控件 [英] Looping through Controls in VB.NET
问题描述
我正在创建一个国际象棋程序.它由六十四个图片框组成,背景颜色为黑白交替.
我将它们命名为 pba1
、pba2
、pbb1
、pbb2
、pbc1
等等上.
现在,我只想遍历黑色的,例如,我只想遍历 pba1、pbb2、pbc3 等等.
如何在 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?
在pba1中,pb代表图片框,a1代表正方形.以防万一,你想知道为什么会有这样的名字.
In pba1, pb stands for picture box, and a1 stands for the square. Just in case, you wonder why such a name.
看看这个答案
推荐答案
在设计时通过表单设计器生成控件仅对受益于表单设计器的布局有意义.
Generating controls at design time via the Forms Designer only makes sense for layouts which benefit from the forms designer.
在您的情况下,您只有 8 行 8 行中的 64 个统一框.不要为此使用表单设计器,在运行时创建控件,并且不要给它们命名像 pba1
,只要把它们放到一个合适的数据结构中(比如一个8x8的数组):
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
这样,您就可以有序地访问字段,而无需通过 Form.Controls
集合.
That way, you can access the fields in an orderly fashion without having to go via the Form.Controls
collection.
这篇关于循环遍历 VB.NET 中的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!