Search code examples
.netarraysvb.netpicturebox

How do I create an array of PictureBox using a loop?


I need to create 49 PictureBoxes and then place them on a Form. I was thinking in something like

Public Class Form1
   Dim grid() as PictureBox
   Public Sub Form_Load () Handles Me.Load
      For i = 0 to 48
         grid(i) = New PictureBox
         grid(i).Visible = True
         Me.Controls.Add(grid(i))
      Next
   End Sub

Debug console tells me grid(i) = Nothing


Solution

  • Dim grid(0 to 48) As PictureBox
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
            For i = 0 To 48
                grid(i) = New PictureBox
                Me.Controls.Add(grid(i))
            Next
        End Sub
    

    or

     Dim grid(48) As PictureBox
            Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
                For i = 0 To 48
                    grid(i) = New PictureBox
                    Me.Controls.Add(grid(i))
                Next
            End Sub
    

    or

    Dim grid() As PictureBox
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
            redim grid(48)
            For i = 0 To 48
                grid(i) = New PictureBox
                Me.Controls.Add(grid(i))
            Next
        End Sub
    

    if you don't like the limit and have to ReDim your array then use a List.

     Dim grid As List(of PictureBox)
            Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
               grid=new list(of picturebox)
                For i = 0 To 48
                    grid.add(New PictureBox)
                    Me.Controls.Add(grid.item(grid.count-1))
                Next
            End Sub