How often do you see this error? If you're like me, you see it a lot. I've seen Microsoft techies get balled up in variations of this error in presentations. Recently, I was coding an example for an article here when I ran into it again. It took me longer than I want to tell you to discover what was wrong.
In this particular case, the code that was creating the error looked like this:
XDoc.Element("myXElements").Add( _
New XElement("myXElements", ContentVar))
In a case like this, the first question that came to mind is, "Which object? There are a bunch of them."
We'll get back to this after looking at exactly what this error is trying to tell you.
In .NET, types are either "value types" or "reference types".
Value types are stored on the directly on the "stack" - a section of memory. Since they're addressed directly, they're initialized when they are created and you don't need a "New" operator for them.
Reference types are objects stored on the "managed heap". They get their name because the variable actually consists of a pointer in memory - a reference - to the location of the object on the heap.
Since reference types are actually pointers to memory, their value can be "Nothing". That is, there is no memory address. This can happen in a variety of ways and that's why this error can be so frustrating. The possibilities include:
- You never assigned anything to the variable.
- You never created an instance of the value assigned to the variable.
- You set the variable equal to Nothing, or a called function did the same thing.
One of the simplest demonstrations uses a string variable (which is a reference type in VB.NET). In the code below, a location for a pointer is created on the heap, but it doesn't point to anything so the value is "Nothing".
Dim a As String
If a.Length = 0 Then
Console.Write("Yes")
End If
The compiler flags a as a problem in this case for you. In my bug above, no such help was available.
In this particular case, the details associated with the NullReferenceException were useless. The fastest way to find the source of the bug was to check each object in the statement with QuickWatch. That (eventually) told me that the actual problem was that I was attempting to add an element to an XML document out of sequence:
<XDoc>
<anotherElement>
<myXElements />
</anotherElement>
</XDoc>
Who knew this would create a null reference exception?

Hi,
Try this code there is no Error:
Dim a As String = “”
If a.Length = 0 Then
MessageBox.Show(a.Length.ToString)
End If
From:
yulyos4vbnet@gmail.com
Exactly. Because in this case you have given a ‘value’ to the reference type by initialing it when you dimension the string. (Even though the value is nothing, it is a value and is no longer null.)
I think Dan is pointing out that if you do not initialize your reference types, you will get the error…his example, with creating an XML document out of sequence, is somewhat esoteric.
I used that example because, as you said, it’s somewhat esoteric. Initially, I had no idea why that error was being reported. It’s an example showing that the error can be created by problems you might not suspect.
Simple!
Try this:
Dim a As String
If len(a) = 0 Then
MessageBox.Show(“Yes!”)
End If
Or this:
Dim a() As String
If a.Length = 0 Then
MessageBox.Show(“Yes!”)
End If
Master, your recommandations are flawed.
The Len() function is obviously coded so that it checks if the input value is Nothing, then it outputs 0. As a c# programmer I balk at this: the length of a null (Nothing) is not 0, it is Nothing. Len() thus makes the assertion that a null string (no string exists) is equivalent to a string of zero length. It’s not unheard of; oracle does this, but it’s not the rule within .NET
Dim a() as String declares an array of strings (but doesnt give it a dimension), not a string! If youre not sure on the difference between an array of strings and a single string, you need to do some background reading on strings.
This blog is NOT saying “oh/ i’m getting this error, please suggest nasty kludges to make it go away” – it is trying to educate on why you cannot declare a viarable to be able to hold an object of a certain type, but if you never actually put an object of that type in there, you cannot call operations on the object. This concept is fundamental to Object Oriented programming
Ja! I say what Matt says too!
(Whew! I’m not going to pick any technical spitting contests with Matt!)
Object reference not set to an instance of an object.
I’ve above error in following statements
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
a.con()
End Sub
I’d like to help, but there just isn’t enough information in your message to allow me to figure out what’s wrong.
What you have (except for “a.con”) is a standard ASP.NET event subroutine. What are you trying to do? Exactly what does the error reference?
am also facing this same error in my code. can u pls help with solution.
Private Sub btnLocOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLocOK.Click
Dim comstring As String = “”
If txtLocation.Text.Trim = “” Then
MsgBox(“Enter the name”)
Exit Sub
End If
‘Dim comstring As String = “”
If cbLocOption.Text.Trim = “ADD” Then
comstring = “Insert into tbl_Location (Location,Ownership) values (‘” + txtLocation.Text.Trim + “‘,’” + cbOwnership.Text.Trim + “‘)”
ElseIf cbLocOption.Text.Trim = “MODIFY” Then
comstring = “Update tbl_Location set Location =’” + txtLocation.Text.Trim + “‘ ,Ownership =’” + cbOwnership.Text.Trim + “‘where LocationID =” + cbLocation.SelectedValue.ToString
ElseIf cbLocOption.Text.Trim = “DELETE” Then
comstring = “Delete from tbl_Location where LocationID =” + cbLocation.SelectedValue.ToString
End If
MsgBox(comstring)
sqlloc(comstring)
Location_Load(sender, e)
cbLocOption_SelectedIndexChanged(sender, e)
End Sub
my email tonny2g@yahoo.com
Since you didn’t give us any real information about where the problem is in your code, it’s a real guessing game. (Visual Basic tells you. Why didn’t you tell us?)
However …….
My guess is that it’s a problem with spacing in your SQL. Here’s what your SQL actually turns out to be:
cblocoption = “ADD”
“Insert into tbl_Location (Location,Ownership) values (‘txtlocation’,'cbOwnership’)”
cblocoption = “MODIFY”
“Update tbl_Location set Location =’txtlocation’ ,Ownership =’cbOwnership’where LocationID =cbLocation”
cblocoption = “DELETE”
“Delete from tbl_Location where LocationID =cbLocation”
The spacing of
=’cbOwnership’where
looks a little hinky to me.
How did if figure this out? Simple. I just plugged it into a VB.NET project and looked at it with the Immediate window.
Never do what you can get the computer to do for you.
I ALSO HAVE THE SAME PROBLEM WITH A DATABASE RELATED PROGRAM:
Dim YOU As DataSet = FOREX.PASTING.VITAModule.GetNewPupil()
Thanks. I was struggling with this error for a while.
I got the same error: “object reference not set to an instance of an object”
Can you please advise what I am doing wrong? I see where the student’s name is being returned when I debug, but the error is received when it attempts to transfer the name to the textbox:
{i.e. Me.txtstudentName.Text = reader.Item(“firstName”) }
Public Sub populateStudentFields(ByVal username As String)
Dim con As New System.Data.SqlClient.SqlConnection
Dim cmdString As String
con.ConnectionString = “server =.\SQLEXPRESS;AttachDbFilename=C:\AddDrop-use\AddDrop\AddDrop\App_Data\AddDrop.mdf;Integrated Security=True;User Instance=True”
cmdString = “Select * from Student_Data where studentId = @Uname”
Dim sqlCmd As New System.Data.SqlClient.SqlCommand(cmdString, con)
sqlCmd.Parameters.Add(“@Uname”, Data.SqlDbType.NVarChar, 24)
sqlCmd.Parameters(“@Uname”).Value = username
Dim reader As System.Data.SqlClient.SqlDataReader
reader = Nothing
Try
con.Open()
reader = sqlCmd.ExecuteReader()
If reader.HasRows Then
reader.Read()
Me.txtstudentName.Text = reader.Item(“firstName”)
reader.Close()
Else
Console.WriteLine(“No rows returned.”)
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
sqlCmd.Dispose()
If IsDBNull(con) Then
con.Close()
End If
End Try
End Sub
I replicated your code (as well as I could without having a copy of your database).
If you code …
Me.txtstudentName.Text = reader.Item(”firstName”)
… with Option Strict On (as it should be), then you get a compiler error because reader returns an Object type which you are trying to assign to a String type (a narrowing conversion). That’s why virtually all texts advise you to explicitly cast the result that is returned to a String before using it.
Me.txtstudentName.Text = reader.Item(”firstName”).ToString
However …
When I turned Option Strict Off just to see what it would do, it still worked because the compiler includes a cast anyway.
So, I’m not sure. All I can speculate at this point is that there is some database error, but I would add the cast anyway.
Thanks Dan.
I took your suggestion, however I got the same error
I found another way to assign the values retrieved from the database to the text box.
I stored the values to a variable, then assign them to their respective text boxes and I am no longer getting the error
Thanks again.
Pretty amazing. Just to be sure, I replicated your code again with my own database. Your former code still works for me.
You’re saying that you replaced the code you have with something like this and it solved the problem:
result.Read()
Dim theStudentNameString As String
theStudentNameString = result.Item(“Ingredient”).ToString
txtstudentName.Text = theStudentNameString
This makes no sense. The error you’re reporting states that some object in the line of code …
Me.txtstudentName.Text = reader.Item(”firstName”)
… has not been instantiated. What object could that be? I’d set a breakpoint and check everything in the line of code in the Immediate window and find out.
The only thing that occurs to me now is that your former code had a spelling error. And, by the way, the “Me” qualifier on the TextBox control isn’t required and is usually not used, but I checked that too and it works for me with and without it.
(The “First, make sure it’s plugged in.” rule applies here. Check the easiest, most obvious things before moving on to more complex things.)
hii Dan,
Sorrry to bother You, But this freaking error has really freaked me out
Here is My code—
Dim connection As String
connection = System.Configuration.ConfigurationManager.ConnectionStrings(“connection”).ToString
Dim strSelect As String
strSelect = “SELECT * FROM leftnav”
Dim con As New SqlConnection(connection)
Dim cmd1 As New SqlCommand(strSelect, con)
Dim reader1 As SqlDataReader
Try
Dim abc1 As String
con.Open()
reader1 = cmd1.ExecuteReader()
reader1.Read()
abc1 = reader1.Item(“parent”).ToString
Response.Write(abc1)
Sports.Text = abc1 ///Here sports is my label id
The problem is it is not assigning the value to that label but it is retrieving data from tabel(i.e here abc1 is assigned the first value from the database)
Exception is:–Object reference not set to an instance of an object.
I replicated your code as well as I could using a database of my own. I works for me.
I assume that what you’re saying is:
Response.Write(abc1) ‘ This statement works
Sports.Text = abc1 ‘ This statement throws the exception
I have no idea why that would happen. As I said, using my own database and substituting my own table and column names, it works.
hi
got the same error,
thank u for your support
Private Sub ProjectReportDataGridView_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles ProjectReportDataGridView.CellFormatting
If e.ColumnIndex = ProjectReportDataGridView.Columns(“riskstatus”).Index Then
If Not e.Value Is Nothing Then
If e.Value.ToString = (“red”) Then
ProjectReportDataGridView.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Red
Else
End If
End If
End If