我可以使用变量来控制我使用的是哪个 PictureBox 吗?

Can I use variables to control which PictureBox I am using?

有没有一种方法可以使用变量来控制我在 Visual Basic 中使用的 PictureBox?

即:

CurrentNumber = 1    
PictureBox(CurrentNumber).backcolour = backcolour

您可以使用 Me.Controls(String) 索引器。它允许您指定要访问的控件的名称(作为字符串),因此您可以通过将字符串 "PictureBox" 与数字连接来动态访问图片框。

Dim TargetPictureBox As PictureBox = TryCast(Me.Controls("PictureBox" & CurrentNumber), PictureBox)

'Verifying that the control exists and that it was indeed a PictureBox.
If TargetPictureBox IsNot Nothing Then
    TargetPictureBox.BackColor = Color.Red
End If

或者,通过避免每次在 Me.Controls 上调用 OfType() extension 时循环遍历整个控件集合来节省处理能力,将结果存储在按控件名称排序的数组中。这样它只需要迭代一次控件集合。

'Class level - outside any methods (subs or functions).
Dim PictureBoxes As PictureBox() = Nothing

'Doesn't necessarily have to be done in a button, it's just an example.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If PictureBoxes Is Nothing Then
        PictureBoxes = Me.Controls.OfType(Of PictureBox).OrderBy(Function(p As PictureBox) p.Name).ToArray()
    End If

    'NOTE: CurrentNumber - 1 is necessary when using an array!
    PictureBoxes(CurrentNumber - 1).BackColor = Color.Red
End Sub

注意: 只有当您的所有图片框都命名为 "PictureBox1"、"PictureBox2" 等时,此解决方案才能正常工作。如果您突然跳过一个数字("PictureBox3", "PictureBox5", "PictureBox6") 然后 PictureBoxes(CurrentNumber - 1) for CurrentNumber = 5 将 return PictureBox6 而不是 PictureBox5

您真正应该做的是创建一个 PictureBox() 并使用它通过索引引用您的图片框。

构建数组的最佳方法是创建一种方法,根据设计者创建的引用构建数组。这使您可以继续使用设计器来创建您的控件,并使您的代码在设计时检查已删除的控件。如果您要查找的控件已被删除,使用 Me.Controls(...) 会出现 运行 次错误。

这是您需要的代码:

Private _PictureBoxes As PictureBox() = Nothing

Sub AssignPictureBoxesArray
    _PictureBoxes = {PictureBox1, PictureBox2, PictureBox3}
End Sub

然后您可以像这样访问它们:

Sub SomeMethod
    Dim CurrentNumber = 1
    Dim PictureBox = _PictureBoxes(CurrentNumber - 1)
    PictureBox.BackColor = System.Drawing.Color.Red
End Sub