Idan Azari
Idan Azari

Reputation: 9

creating an array of controls with unknown size at vb.net

So I need to create an array of labels and I dont know the final size of the array. I declare it in the class section

Dim myPoints() As Label

in the program I fill the array

 Dim l As New Label
       
        l.Width = 4
        l.Height = l.Width
        l.BackColor = Color.Red
        l.Visible = True
        l.Left = pointA.X - 2
        l.Top = pointA.Y - 2
        l.Name = CStr(i)
        myPoints(i) = New Label
        myPoints(i) = l
        AddHandler l.Click, AddressOf l_Click
        Panel1.Controls.Add(myPoints(i))

when I run the program I get object reference not set Error is there a way to to do it with no declaration of the array size ?

Upvotes: 0

Views: 127

Answers (1)

David
David

Reputation: 6111

Arrays are fixed length collections. If you need a collection that can grow and/or shrink, then use a List(Of T) (documentation)

Dim myPoints = New List(Of Label)()
Dim l = New Label() With {
    .Width 4,
    .Height = .Width,
    .BackColor = Color.Red,
    .Visible = True,
    .Left = pointA.X - 2,
    .Top = pointA.Y - 2,
    .Name = i.ToString()
}
myPoints.Add(l)

Upvotes: 1

Related Questions