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"

5
  • possible duplicate of What is a NullReferenceException in .NET? Commented Aug 9, 2012 at 4:02
  • Have you tried using the debugger? Commented Aug 9, 2012 at 4:03
  • i think its about that the text box is empty, but i want to fill it when i show the form..how can i get over this? Commented Aug 9, 2012 at 4:06
  • It's really hard to answer you, since the problem is that you don't understand the basics of the form lifecycle. Commented Aug 9, 2012 at 4:10
  • i solved it by making the array a local variable then passing it to a function, thanks anyway Commented Aug 9, 2012 at 4:16

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

how would you solve this keeping the array as public variable?
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(",")
Great! Glad to be able to help.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.