Question:
What is wrong with this vb.net code?
Andrew M
2009-11-24 15:15:34 UTC
i am trying to make a program that just says the persons name that they type into the box then "hi"

Public Class Form1
Dim aname As String = TextBox1.Text
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(aname, "hi")
End Sub
End Class

it is giving me this error. "An error occurred creating the form. See Exception.InnerException for details. The error is: Object reference not set to an instance of an object."
Three answers:
Helpful Harry
2009-11-25 08:51:40 UTC
MsgBox(TextBox1.Text, "Hi")



Dane
Ratchetr
2009-11-24 23:29:21 UTC
You made aname a class variable, and initialized it.

So the initializer will run as soon as the Form1 class is created.

But when the form is being created, TextBox1 doesn't have a value yet. That doesn't happen until much later in the game, when the form is being created. Since TextBox1 will be null, the attempt to access TextBox1.text will generate the exception you are seeing.



Fix is easy enough:

move that line of code inside your button click handler.
prx_187
2009-11-24 23:21:40 UTC
Hello,



Difficult to say like this.. is it a web application or just a windows application?



You can have a look to the code project site, they have some .net tutorials.



Hope it helps


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...