将多个PictureBox添加到数组

时间:2017-05-10 16:11:14

标签: vb.net

所以我总共想要添加55个PictureBox个数组。它们的命名如下:

Row1_Brick1Row1_Brick2,最多Row1_Brick10

总共有10行,每行的砖少1个。

到目前为止,我已经想到了这项工作:

Dim bricks(0 To 54) As PictureBox 'Total of 55 Bricks Spread Out

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    'Start of Loading 55 Bricks into the bricks() Array
    For i = 0 To 54
        For a = 1 To 10
            For am = 10 To 1 Step -1
                 bricks(i) = ("Row" & a & "_Brick" & am)
            Next
        Next 
    Next 
End Sub

关于如何做到这一点的任何想法都会很棒。

2 个答案:

答案 0 :(得分:1)

我推荐一个锯齿状的数组,看起来像这样(请注意,这是0索引而不是1索引,与控件名称一样):

_ENV

但是,如果你真的只想要一个阵列,那么它至少更容易设置(你可以将它归结为一行):

cf ssh

如果需要,您可以进行 Dim bricks(10)() As PictureBox Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 'Set up child arrays For i As Integer = 0 To 9 bricks(i) = New PictureBox(9-i) 'Set up each element in the array For j As Integer = 0 To 9 - i bricks(i)(j) = Me.Controls("Row" & i + 1 & "_Brick" & j + 1) Next j Next End Sub 调用以限制名称与您的模式匹配的图片框,但最好将这些控件放入可用作公用Panel或GroupBox父母而不是形式。您还可以使用Dim bricks() As PictureBox Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load bricks = Me.Controls.OfType(Of PictureBox)().ToArray() End Sub 调用来确保以正确的顺序返回PictureBox:

Where()

如果你与Linq函数不一致,那么诀窍是将结果数组索引作为内部循环的一部分递增,而不是单独使用一个单独的循环:

Orderby()

答案 1 :(得分:0)

这是完全未经测试的,因为我太懒了,无法创建新项目并以与您相同的方式设置表单,但它应该关闭

Dim arr(54) As PictureBox
Dim index As Integer = 0
For row As Integer = 1 To 10
    For col As Integer = 1 To 10 - row + 1 'Max column is based on the inverted value of the current row
        arr(index) = Ctype(f.Controls("Row" & row & "_Brick" & col), PictureBox)
        index += 1
    Next
Next

这种通过名称明确获取控件的方法可以避免由于控件添加到表单的顺序而导致的任何错误。