Pergunta

I wan't to create a bunch of variables inside a While, each one with different names.

Here is what i tried:

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

I want that it creates the Picturebox1 Picturebox2 ... and so on, but the "asd" variable won't evaluate and the code won't work. How could you create variables with different names in a loop with Visual Studio?

Foi útil?

Solução

What I've done in the past is something like:

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

This is a very basic example and your linq would probably be more dynamic than the one I used but you should get the idea. In this case I'm assuming that you are just putting the PictureBoxes on the form, if this isn't the case then you will need to linq through whichever collection you are adding the controls to.

Edit #1:

As far as events are concerned you will need to add the handlers manually. So your code would become:

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

And the FunctionToHandleClick would look like this:

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

Outras dicas

Why don't you use an Array?

Dim pictureboxes(5) As PictureBox

For i As Integer = 0 To 5
    pictureboxes(i) = New PictureBox()
Next
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top