我可以使用变量来控制使用哪个PictureBox吗? [英] Can I use variables to control which PictureBox I am using?

查看:89
本文介绍了我可以使用变量来控制使用哪个PictureBox吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way that I can use a variable to control which PictureBox I am using in Visual Basic?

即:

CurrentNumber = 1    
PictureBox(CurrentNumber).backcolour = backcolour

推荐答案

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

You can use the Me.Controls(String) indexer. It lets you specify the name (as a string) of the control you want to access, thus you can dynamically access a picture box by concatenating the string "PictureBox" with a number.

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

或者,通过避免每次调用

Alternatively, to save processing power by avoiding looping through the entire control collection every time you can call the OfType() extension on Me.Controls, storing the result in an array sorted by the controls' names. That way it'd only have to iterate the control collection once.

'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.

NOTE: This solution will only work properly if all your picture boxes are named "PictureBox1", "PictureBox2", etc. If you suddenly skip a number ("PictureBox3", "PictureBox5", "PictureBox6") then PictureBoxes(CurrentNumber - 1) for CurrentNumber = 5 would return PictureBox6 rather than PictureBox5.

这篇关于我可以使用变量来控制使用哪个PictureBox吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆