在循环上创建具有不同名称visual的变量

时间:2014-05-10 18:28:45

标签: vb.net visual-studio-2010

我不想在While内创建一堆变量,每个变量都有不同的名称。

这是我试过的:

 Dim asd As Integer = 1
    While asd < 5
        Dim picturebox +asd As New Picturebox
    End While

我希望它能创建Picturebox1 Picturebox2 ......等等,但是&#34; asd&#34;变量不会被评估,代码也不会起作用。如何使用Visual Studio在循环中创建具有不同名称的变量?

2 个答案:

答案 0 :(得分:1)

我过去做过的事情就像:

For i = 0 to 5
    Dim t As New PictureBox()
    t.Name = "PictureBox" & i
    Me.Controls.Add(t)
Next
Dim picToChange = From r in Me.Controls Where Typeof(r) Is PictureBox AndAlso r.Name = "PictureBox1" Select r
If picToChange IsNot Nothing AndAlso picToChange.Any Then
    'Do Something
End If

这是一个非常基本的示例,您的linq可能比我使用的更动态,但您应该明白这一点。在这种情况下,我假设您只是将PictureBoxes放在表单上,​​如果不是这种情况,则需要linq通过您添加控件的任何集合。< / p>

编辑#1:

就事件而言,您需要手动添加处理程序。所以你的代码将成为:

For i = 0 to 5
    Dim t As New PictureBox()
    t.Name = "PictureBox" & i
    AddHandler t.Click, AddressOf(FunctionToHandleClick)
    Me.Controls.Add(t)
Next
Dim picToChange = From r in Me.Controls Where Typeof(r) Is PictureBox AndAlso r.Name = "PictureBox1" Select r
If picToChange IsNot Nothing AndAlso picToChange.Any Then
    'Do Something
End If

FunctionToHandleClick看起来像这样:

Private Sub FunctionToHandleClick(ByVal sender As Object, ByVal e As ClickEventArgs)
End Sub

答案 1 :(得分:0)

为什么不使用Array

Dim pictureboxes(5) As PictureBox

For i As Integer = 0 To 5
    pictureboxes(i) = New PictureBox()
Next