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

时间:2017-11-19 06:22:05

标签: vb.net variables picturebox

有没有办法可以使用变量来控制我在Visual Basic中使用哪个PictureBox?

即:

CurrentNumber = 1    
PictureBox(CurrentNumber).backcolour = backcolour

3 个答案:

答案 0 :(得分:1)

您可以使用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) CurrentNumber = 5将返回PictureBox6而不是PictureBox5 composer require league/flysystem composer require league/flysystem-aws-s3-v3 composer require creocoder/yii2-flysystem composer require mihaildev/yii2-elfinder composer require mihaildev/yii2-elfinder-flysystem

答案 1 :(得分:1)

你真正应该做的是创建一个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

答案 2 :(得分:0)

查看PictureBox类的API docs,有一些例子。

我对VB几乎一无所知,但构造函数New PictureBox将返回一个PictureBox类的实例,您可以将其作为变量进行跟踪。

类似

Dim my_pic_box = New PictureBox
my_pic_box.BackColor = some_background_color

但你可能想要一个PictureBox的数组,所以类似于:

Dim picboxs(2) As PictureBox
picboxes(0) = New PictureBox
picboxes(0).BackColor = some_background_color
picboxes(1) = New PictureBox
picboxes(1).BackColor = some_background_color2

对于数组,使用循环会更好。取决于您如何使用这些对象。如果它们被标记为UI的一部分,我根本不会将它们放在数组中,而只是将它们设为个体Dim。如果基于某些其他输入生成它们,并且它们的数量在运行时更改,则使用数组。