0

i wonder what is wrong with the following vb.net code.

Public Class Form10

Public IDs() As String = TextBox1.Text.Split(",")

Private Sub Form10_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    For Each id In IDs
        MsgBox(id)
    Next
End Sub

End Class

when i do

Form10.show()

i get an error "Object reference not set to an instance"

user1570048
  • 880
  • 6
  • 35
  • 69

2 Answers2

1

You have declared a field in your class to be initialized with a value from a control on the corresponding form that does not yet exist. The control is not initialized and loaded by the time your initializer on your field member is accessed, thus causing the error.

To keep the public IDs declaration, you could remove the initialization from the field declaration, then move the assignment to the Button1_Click event, as follows:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    IDs=TextBox1.Text.Split(",")
    ' Do something interesting with IDs now...
End Sub
David W
  • 10,062
  • 34
  • 60
  • how would you solve this keeping the array as public variable? – user1570048 Aug 09 '12 at 04:34
  • 1
    Since the code has no way of knowing when the textbox is populated, it will have to be done as a result of user action, eg a button click. Keep the field declaration, omit the initialization, and move the Split code into the _Click event of Button1, eg: IDs=TextBox.Text.Split(",") – David W Aug 09 '12 at 04:38
  • Great! Glad to be able to help. – David W Aug 09 '12 at 05:01
0
Public Class Form10
Private Sub Form10_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim IDs() As String = TextBox1.Text.Split(",")
    Form1.somefunction(IDs)
End Sub

and in Form1

  Public Sub somefunction(ByVal IDs() As String)
    For Each id In IDs
        MsgBox(id)
    Next
End Sub
user1570048
  • 880
  • 6
  • 35
  • 69