1. Technology

Object reference not set to an instance of an object.

By October 19, 2008

Follow me on:

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
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:

        <myXElements />

Who knew this would create a null reference exception?

October 26, 2008 at 4:53 am
(1) yulyos says:


Try this code there is no Error:

Dim a As String = “”
If a.Length = 0 Then
End If


October 26, 2008 at 9:59 am
(2) Timothy Rupp says:

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. ;)

October 26, 2008 at 3:34 pm
(3) visualbasic says:

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.

January 21, 2009 at 10:53 am
(4) Master says:


Try this:

Dim a As String
If len(a) = 0 Then
End If

Or this:

Dim a() As String
If a.Length = 0 Then
End If

January 15, 2010 at 8:38 am
(5) Matt says:

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

January 16, 2010 at 11:19 am
(6) visualbasic says:

Ja! I say what Matt says too!

(Whew! I’m not going to pick any technical spitting contests with Matt!)

March 3, 2010 at 6:35 am
(7) harshal says:

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
End Sub

March 3, 2010 at 11:23 am
(8) Dan Mabbutt says:

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?

May 24, 2010 at 10:52 pm
(9) reliq says:

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
Location_Load(sender, e)
cbLocOption_SelectedIndexChanged(sender, e)
End Sub

my email tonny2g@yahoo.com

May 25, 2010 at 10:05 am
(10) visualbasic says:

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


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.

July 21, 2010 at 8:08 am

Dim YOU As DataSet = FOREX.PASTING.VITAModule.GetNewPupil()

October 3, 2010 at 4:15 pm
(12) M Mahdi says:

Thanks. I was struggling with this error for a while.

June 20, 2011 at 2:57 pm
(13) NewDev says:

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

reader = sqlCmd.ExecuteReader()
If reader.HasRows Then
Me.txtstudentName.Text = reader.Item(“firstName”)

Console.WriteLine(“No rows returned.”)
End If

Catch ex As Exception
If IsDBNull(con) Then
End If
End Try

End Sub

June 20, 2011 at 10:32 pm
(14) Dan Mabbutt says:

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.

June 21, 2011 at 10:31 am
(15) NewDev says:

Thanks Dan.

I took your suggestion, however I got the same error

June 21, 2011 at 5:41 pm
(16) NewDev says:

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.

June 22, 2011 at 9:44 am
(17) Dan Mabbutt says:

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:

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.)

July 25, 2011 at 3:43 am
(18) Pranshu says:

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

Dim abc1 As String
reader1 = cmd1.ExecuteReader()
abc1 = reader1.Item(“parent”).ToString

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.

July 25, 2011 at 4:18 pm
(19) Dan Mabbutt says:

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.

September 4, 2012 at 8:30 am
(20) hatim says:

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
End If
End If
End If

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>
  1. About.com
  2. Technology
  3. Visual Basic

©2014 About.com. All rights reserved.