首页 > 解决方案 > 我正在尝试将图片框添加到数组中,以便稍后在以编程方式创建它们时引用它们

问题描述

到目前为止,我只有这段代码......

Dim lineb As New PictureBox
lineb.Size = New Size(24, 24)
lineb.BackColor = Color.FromArgb(0, 192, 192)
lineb.Location = New Drawing.Point(xb, yb)
Controls.Add(lineb)
lineb.Name = "lineb" + CStr(creatorb)
creatorb += 1

这会在 timer.tick 事件中生成无限行的图片框。Xb 和 Yb 连续移动,这很有效。我需要弄清楚如何将每个图片框添加到数组或稍后引用它们的另一种方式。每个都被创建并重命名为 lineb +​​ 1...2...3...4... 等。

标签: vb.netvisual-studio

解决方案


下面是一个跟踪动态创建的控件的方法示例。这比将每个控件添加到数组更容易。

Dim pbox as New PictureBox
With pbox
     .location = New Point(xb, yb)
     .size = New Size(24, 24)
     .Tag = "box1" 'choose a tag that will help identify it later
     ' and so on
     Addhandler pbox.click, AddressOf pbox_click '' to add a click event handler  
End With
Me.Controls.add(pbox)


Private Sub pbox_click(sender As Object, e As EventArgs)

    Dim the_sender As PictureBox = DirectCast(sender, PictureBox)
    Dim reference As String = DirectCast(the_sender.tag, String)

    ''' do whatever you need to do now that you know which picturebox was clicked.

End Sub

或者,您可以随时循环浏览控件以找到您要查找的控件:

 For Each Ctrl As Control In Me.Controls

     If TypeOf Ctrl Is PictureBox Then

         If ctrl.tag = "box1" Then '''or whetever you are looking for

             ''' do your stuff here                     

         End If

     End If

 Next

推荐阅读