0

I want to display a row of labels onto my form that the user defines. An example would be the user enters that he/she wants to display 6 labels so the for each loop would go through a list of label objects and create them.

I have tried to use arrays and lists, the user would enter how many labels and it the loop would set their properties like location but I would get this error. System.NullReferenceException: 'Object reference not set to an instance of an object. I already tried to search this up but the results are not what im looking for and I don't know how to instantiate multiple controls at once.

 Dim People As Integer
 Dim wordlength As Integer
 Dim wordChar As Integer
 Dim list As New List(Of Label)

 wordlength = CInt(InputBox("Enter your Words length"))

 Dim CharAmount(wordlength) As Label
 Dim addon As Integer = 0

    For Each item As Label In CharAmount
        list.Add(item)
    Next


    For Each item As Label In list
        With item
            .Size = New Size(30, 30)
            .Location = New Size(324 + addon, 20)
        End With
        addon += 20
        Me.Controls.Add(item)
    Next

The program has to display a inputed amount of labels in a row

1 Answers1

0

You need create a label before use.

For i = 1 to wordlength 
    Dim item As New Label() 
    list.Add(item)
Next
shingo
  • 18,436
  • 5
  • 23
  • 42
  • Thanks, I don’t undestand the Dim item as New label part though. Aren’t you adding the same thing over again? – Sparshs Jan 15 '19 at 04:24
  • How can it be adding the same thing every time? It's creating a `New Label` inside the loop, so each iteration will create a `New Label`. You'd only be adding the same thing over and over if you just created one `New Label` outside the loop and then added that inside the loop. – jmcilhinney Jan 15 '19 at 04:25