System.NullReferenceException: 'Object reference not set as an instance of an object.' [duplicate]

0

I would like if someone could help me with the following question. I'm doing a test program in which there is a textbox in which names are inserted, these names must be saved in an array and then pressing another button that those names go to a listbox.

When I run the program and try to add names to the array, VS throws me the error: System.NullReferenceException: 'Object reference not set as an instance of an object.'

I think the problem may be that I'm not creating a new instance of the Name array. In c # it would be something like "string [] Names = New String [1000]", but in VB I do not know how it is done, I searched for information on the internet and tried translating from c # to VB and so far without success. What could be the solution?

 Public Class Form1
Dim Nombre As String()
Dim Counter As Integer = 0

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles button1.Click
    Counter = Counter + 1
    Nombre(Counter) = textBox1.Text

End Sub

Private Sub button2_Click(sender As Object, e As EventArgs) Handles button2.Click
    For Each A As Integer In Nombre
        ListBox1.Items.Add(Nombre(a))

    Next

End Sub
 End Class

Thanks in advance.

    
asked by Erick Estevez 05.11.2018 в 22:43
source

1 answer

2

To create a vector of 1000 positions as you explained, you should do something like this:

Dim Nombre(1000) As String
Dim Counter As Integer = 0

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Counter = Counter + 1
    Nombre(Counter) = textBox1.Text
End Sub

Anyway, I recommend using lists to avoid having the problem of the limits of the array, that is, something like this:

Dim Nombre As List(Of String)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Nombre.Add(TextBox1.Text)
End Sub

Good luck!

    
answered by 05.11.2018 / 23:19
source