0

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

RicRev
  • 29
  • 1
  • 1
  • 8

1 Answers1

2
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
  • 3
    it's not grid(i) that is nothing. it is grid() that is not initialized –  Oct 31 '17 at 00:20
  • How is this any different from what I'm doing? You're just limiting the array size to 49. – RicRev Oct 31 '17 at 00:36
  • you are asking for help. I gave you the answer in the comment on why your code isn't working. I'm not limiting the array. I'm initializing it –  Oct 31 '17 at 00:37
  • @RicRev He's not limiting the array size. He's giving it any size at all. Without the size, all you have is a variable reference that doesn't point to anything. If you're used to a language like javascript, where arrays are dynamic, those aren't real arrays in the formal computer science sense at all. They are _collections_ with some array-like properties. Real arrays have a fixed size. But even this won't work. You also want to set a position for each PictureBox, or they'll all be stacked on top of each other at position (0, 0). – Joel Coehoorn Oct 31 '17 at 00:43
  • Oh, and VB.Net defines arrays using the index of the last item, not the number of items. So an array with 49 items (indexes from 0 to 48) is declared using a 48 subscript. – Joel Coehoorn Oct 31 '17 at 00:46
  • @RicRev no problems buddy. thanks for voting up the answer. –  Oct 31 '17 at 00:55