Raymond Lewallen

Sponsors

The Lounge

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.

Every once in awhile, you come across this exception: System.NullReferenceException – “Object reference not set to an instance of an object.”  You see people asking about this everywhere; about why are they getting this error.  Below are a few common causes for this.


Note, regardless of the scenario, the cause is always the same in .Net: You are trying to use a reference variable who's value is Nothing/null.  When the value is Nothing/null for the reference variable, that means it is not actually holding a reference to an instance of any object that exists on the heap.  You either never assigned something to the variable, never created an instance of the value assigned to the variable, or you set the variable equal to Nothing/null manually, or you called a function that set the variable to Nothing/null for you.

1. In VB.Net, you are trying to access a string that has not been initialized.  In C#, this isn’t possible.  You can’t even compile code like the following in C#

C# won't compile this

                        private void TestString()

                        {

                                    string a;

                                    if (a.Length == 0)

                                    {

                                                Console.WriteLine("Yes");

                                    }

                        }

However, in VB.Net, you can compile the equivalent, and that lead right down a road to the mentioned exception.

VB will compile, but throw a runtime exception.

    Private Sub TestString()

        Dim a As String

        If a.Length = 0 Then

            Console.Write("Yes")

        End If

    End Sub 

Remember, a string is a reference type (a character array) that has to have a value.  You don’t have to use the “new” keyword, but by default the value is Nothing/null.  You would have to at least initialize to a = String.Empty, or to some other actual value, before it will compile in C#, or run without exception in VB.Net

To fix this above problem in VB.Net, set [a = “something”] before you attempt to do anything with it.

2. You never created a new instance of an object.  Again, this is code that C# will not compile, but VB.Net will, and throw a runtime error.  Same as a string, any reference type must be initialized.  Strings and some other CTS types have a misconception of being value types, like Integers, and they are not.

C# will not compile.

                        private void TestObject()

                        {

                                    ArrayList b;

                                    b.Add("Hello");

                        }

Here is the VB equivalent, that will compile, but throw the mentioned exception.

VB will compile but throw an exception.

    Private Sub TestObject()

        Dim b As ArrayList

        b.Add("Hello")

    End Sub

To fix the problem, you need to say [Dim b As New ArrayList] in the above code.

3.  You created the object, but killed it too soon.  Here is a simple example of that.

Don't kill objects too soon.

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

        TestObject()

        ShowCount()

    End Sub

 

    Dim b As New ArrayList

 

    Private Sub TestObject()

        b.Add("Hello")

        b = Nothing

    End Sub

 

    Private Sub ShowCount()

        Console.Write(b.Count.ToString())

    End Sub

A more complex example would be that you disposed of a class that maybe you use to access the database.  This killed the connection and command objects.  But then, somewhere else, you tried to call a method of that class that used those objects that no longer exists.  Again, same exception gets thrown, but coming from withing the instantiated class itself.

c = a.GetOrders() will throw an exception.

Public Class Class2

 

    Dim a As New MyDataAccessObjects.Customers

    Public Sub New()

        LoadData()

        LoadMoreData()

    End Sub

 

    Private Sub LoadData()

        Dim b As New Collection

        Try

            b = a.GetCustomers()

        Finally

            a.Dispose()

        End Try

    End Sub

 

    Private Sub LoadMoreData()

        Dim c As New Collection

        Try

            c = a.GetOrders()

        Finally

            a.Dispose()

        End Try

    End Sub

 

End Class 

The GetOrders function inside of Customers requires an instance of a connection, but you disposed of the required objects required to access the database back up in LoadData() when you called a.Dispose().  Be careful when you clean up your instances, that you are not using them again somewhere.  This is most common in classes where you are using class-wide instantiated objects.  If you create and drop your objects within each method, this isn’t going to be a problem, and you are actually following a better guideline by creating at the last necessary moment, and destroying at the first possible moment, not to mention avoiding possible exceptions like InvalidReferenceException.


Posted 06-23-2005 9:03 AM by Raymond Lewallen

[Advertisement]

Comments

Ben Reichelt wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-23-2005 10:34 AM
its interesting to note that if you modify your first example to read:

string a = null;
if (a.Length == 0)
{
Console.WriteLine("Yes");
}

Then this will compile, even though the same error will occur.
Kanchana wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-01-2005 1:56 AM
I am getting this error in the view designer, when I derive one user control from another. Do you know how I can solve this?
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-01-2005 3:33 AM
Kanchana,

The error is always caused by the same reason - trying to use a variable before it points to an existing reference object. Send me some of the code you are having trouble with via my "Contact" link at the top of this page. I'll be out of town until July 4th, so there will be a delay in getting back to you.
mike wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-05-2005 10:16 PM
in vb.net i have code that instantiated a dll w/ no problems (even though i am still coding and testing), then all of a sudden i am getting the 'object reference' error. do you have a few minutes to run through my code-one function. thanks!
mike
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-06-2005 5:58 AM
Mike, send me your code via my Contact form from the link at the top of this page. I'd be happy to look at it. You can also post it on our forums in the VB section if you'd like.
Eric Newton wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-15-2005 10:23 AM
Whoa... stop the press

DateTime isnt a ValueType? since when?

And to muddy up the waters even more, how about the generic Nullable types: half reference and half valuetypes...
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-15-2005 10:48 AM
LOL Eric! I musta been drunk or sleepy when I wrote that. I was like "WTF is he talking about?" then I went back and read it. I took that out :)
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-15-2005 10:50 AM
Oh, and I didn't want to get into generics. Most people who understand generics aren't looking for this type of information as they already understand how it all works and why this exception occurs.
Romi wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-18-2005 11:15 PM
You've helped me discovered my blind spot for Common Cause No. 2! Thanks =)
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-19-2005 5:58 AM
Glad to be of help Romi :)
Badal Kumar wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-18-2005 5:55 AM
Thanks a lot, u help me to understand the problem of Null
ReferenceException. But still I am not geting the solution of my problem. If u have any kind of solution regarding my problem plz help me.
Problem:- Actually I use nested datagrid, when i open it in edit mode its gives the problem of NullReferenceException.My code is as follows:
Public Sub DataGrid1_EditCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
DataGrid1.EditItemIndex = e.Item.ItemIndex
gridProducts.EditItemIndex = e.Item.ItemIndex
BindData()
End Sub

Here DataGrid1 is our outer DataGrid and gridProducts is our inner Datagrid.
Plz give me suggestion, how i will come out from this problem.

Email :- badal.kumar@gmail.com
Ceema wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-21-2005 6:28 PM
Thanks Raymond, it helped me to fix my problem

Ceema
Serge wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-30-2005 5:40 PM
Hi Raymond,

I get "Object reference not set to an instance of an object" AFTER I've tested to see if it's nothing, like so:

If oSC.MyObject Is Nothing Then Return sErrorMsg
With oSC.MyObject '<-- Error here
...
End With

Any idea how it could be NOT nothing, then give me "Object reference not set to an instance of an object" once I try to use it?

Thanks!
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-04-2005 10:00 AM
Serge, not sure what that would be. Try not using the With at all and see if when you access the object, you still get the exception. What happens when you use With, is that a new reference pointer to the address space on the heap is created. With is saying that when it tries to create a new reference pointer, that there is nothing in that address space. But the line prior confirms that the address space is indeed occupied. So just remove the With...End With and use the object normally and see what happens.
Gary wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 11-17-2005 12:44 PM
Your comments are very concise and informative. Do I infer from what you wrote that this error should occur every time the logic is executed? In my case, I get the error (catastrophic yellow server error page) intermittently and not necessarily in the same area of code. Additionally, the error only seems to be occurring recently on a production system that never experienced it before. Any suggestions?
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 11-22-2005 9:51 AM
Gary, you're just going to have to step through the code and find out where it might be occuring. That's really what it boils down to. Usually when things look intermittent, they really aren't. Its due to multiple linear paths of execution for a method (cyclomatic complexity) due to If..Else statements and switch statements and you just have to find out which path is executing that is causing the problem.
Tisha Phillips wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-14-2005 12:28 PM
Hi. I am having the same type of problem with a section of code for my VB Final project. I can't figure it out.
Here's the section where I'm having the problem:
Private Sub btnList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnList.Click
Dim choice As String
Dim searchString As String
Dim dRow As DataRow
Dim iRecNum As Short
Dim matches As Short

lstResults.Items.Clear()

choice = lstyears.SelectedItem
Select Case choice
Case Is <= choice
For Each dRow In DsStateSet1.Tables("admitted").Rows
If Not (dRow.Item("admitted") Is DBNull.Value) Then
Me.BindingContext(DsStateSet1, "Admitted").Position = iRecNum
DatabaseMoved()
OriginalRecords(matches) = iRecNum
matches += 1
lstResults.Items.Add(dRow.Item("State"))
End If
iRecNum += 1
Next
Case Is >= choice
For Each dRow In DsStateSet1.Tables("Admitted").Rows
If Not (dRow.Item("admitted") Is DBNull.Value) Then
Me.BindingContext(DsStateSet1, "Admitted").Position = iRecNum
DatabaseMoved()
OriginalRecords(matches) = iRecNum
matches += 1
lstResults.Items.Add(dRow.Item("State"))
End If
iRecNum += 1
Next

End Select

The error is catching on the "For Each" statement. Any suggestions would be helpful.

email: purplefrog_lover@hotmail.com

Thanks so much!
hui wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 01-23-2006 8:19 AM
Help.!!

An error occur here!! Cant see anything wrong lei

Th error is System.NullReferenceException - Object reference not set to an instance of an object

Dim ok As Button
ok.Attributes.Add("onclick", "return confirm('Are you sure you want to login?');")
Response.Redirect("CheckOverdue.aspx")
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 01-23-2006 9:38 AM
Hui,

Dim ok as New Button
Boulent Mustafa wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-08-2006 6:09 AM
I get the System.NullReferenceException on this line

Dim BalanceRequest As New Betfair.GetAccountFundsReq, this is how the variable is declared

BalanceRequest.header.clientStamp = Int(0) and this is the line that causes the error.


Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-12-2006 10:27 PM
Boulent,

What is the code behind clientStamp?
Nelson Hall wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-14-2006 1:39 PM
I get the "Object reference not set to an instance of an object error" on an application that runs fine for a few days and then this error happens. I then have to go kill the aspnet_wp.exe process to get the application to work again. If it were a code problem I would expect consistent behavior. Any ideas on why this might be happening?

Thanks,

Nelson
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-14-2006 4:42 PM
Nelson,

There is no way of knowing without seeing the code.
Malcolm wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-24-2006 10:44 AM
Thanks very much. I was getting this error but the cause was slightly different although at the root of it I'm sure it was the same.

Every time I tried to load my streamwriter I got the error.

Dim sw as StreamWriter
sw = New StreamWriter(ConfigurationSettings.AppSettings("ertFile")) '<-- DIES HERE.

It would die on the second line there which is what's supposed to fix the error. Problem was a I didn't close the StreamReader for the ertFile and the contention results in this error.
Chandu wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 03-24-2006 11:17 AM
Hello this is the error i am getting:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 52:          Dim sql As string
Line 53:           Dim dbconn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & Server.MapPath("proposal1.mdb"))
Line 54:            sql = "insert into prop (one,two,three,four,dept,title,fagency,tamount,sdate,duration,icostrate,mreq,cels,uri,external) Values ('" & Request("investigator1").ToString & "','" & Request("investigator2").ToString & "','" & Request("investigator3").ToString & "','" & _
Line 55:                                     Request("investigator4").ToString & "','" & Request("dept").ToString & "','" & Request("title").ToString & "','" & _
Line 56:                                     Request("fagent").ToString & "','" & Request("tamount").ToString & "','" & Request("startdate").ToString & "','" & _


Source File: E:\Intranet\forms\proposalform.aspx.vb    Line: 54

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
  proposal.add_submit(Object s, ImageClickEventArgs e) in E:\Intranet\forms\proposalform.aspx.vb:54
  System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +109
  System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +69
  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
  System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
  System.Web.UI.Page.ProcessRequestMain() +1292


I dont know where the hell its going wrong. Could you please help me out.
Thanks,
Chandu
aviand wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 04-03-2006 11:08 AM
Thanks for the great! explanation of this topic. I believe it has helped me narrow in on the reason I am getting this exception but I am still unable to resolve the issue.

I am writing an ASP.Net app using language=vb in VS.Net 2003 IDE and trying to call an exported function from an unmanaged dll (written in PowerBasic). The unmanaged dll is an interface between any external code such as mine and some legacy code which only uses null terminated fixed length strings.
I am able to call functions with only numeric parameters but this particular function is defined with fixed length string buffers and I believe is causing the NullReferenceException because of a mis-match in my declare and the exported function definition.

I have to declare Integer variables for those exported as Long because the exported function needs a 32 bit integer not a 64 bit. The numerics are not giving me problems. It is the strings.

Here is the exported definition:
Declare Auto Function DataInterFace Lib "azCOMMS.DLL" Alias "DATAINTERFACE" _
       (ByVal lResults As Long, ByVal  sBuffer As String * 4096, ByVal iPort As Long, _
           ByVal sServer As String * 128, ByVal lTimeOut As Long, ByVal sUser As String * 50) As Long

and here is my declare in a class module:
Declare Auto Function DataInterFace Lib "azCOMMS.DLL" Alias "DATAINTERFACE" _
       (ByVal lResults As Integer, ByVal  sBuffer As String, ByVal iPort As Integer, _
           ByVal sServer As String, ByVal lTimeOut As Integer, ByVal sUser As String) As Integer

Do you have any suggestions on how I can declare this function so I can pass it fixed length strings?

I have looked into CChar() and VBFixedStringAttribute() but cannot get them to work.
I have read about VB6.FixedLengthString() but can't find the reference I need to include.

Thanks.
Russ wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 04-06-2006 4:13 PM
Its great when you can find answers to error messages that make you go "HUH???????????????????"
Vishu wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 04-20-2006 7:04 AM
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 110:
Line 111:        Dim objSriLankaLeastFare As New LeastFareLankaServices.Service1()
Line 112:        objSriLankaLeastFare.getClasses(Trim(Request("DestFrom")), Trim(Request("DestTo")), Trim(Request("dptDate")), Trim(Request("dptMonYr")), Trim(Request("retDate")), Trim(Request("retMonYr")), Session("TA"), Trim(Request("airline")), "1", "ReturnFlight", "MyQatar")
Line 113:        EconomyPriceAndClass = objSriLankaLeastFare.showResultsEconomy()
Line 114:        BusinessPriceAndClass = objSriLankaLeastFare.showResultsBusiness()


Source File: c:\inetpub\wwwroot\MyQatar_net\flightOnlyOneWay\fltResultOneway.aspx.vb    Line: 112

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
  LeastFareLankaServices.Service1.ReturnRecords(String TA, String databaseName)
  LeastFareLankaServices.Service1.getClasses(String destFrom, String destTo, String dptDate, String dptMonthYr, String retDate, String retMonthYr, String TA, String Airline, String FlightType, String OneWayOrReturn, String databaseName)
  MyQatar_net.fltResultOneway.Page_Load(Object sender, EventArgs e) in c:\inetpub\wwwroot\MyQatar_net\flightOnlyOneWay\fltResultOneway.aspx.vb:112
  System.Web.UI.Control.OnLoad(EventArgs e)
  System.Web.UI.Control.LoadRecursive()
  System.Web.UI.Page.ProcessRequestMain()




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:1.1.4322.2032; ASP.NET Version:1.1.4322.2032
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 04-20-2006 8:33 AM
Chandu,

In your watch window, right before you get to line 54, make sure you can read in each of those Request varirables.  Looks like one might be missing.
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 04-20-2006 8:33 AM
Vishu,

Right before you get to line 112, set a breakpoint, and load those Request values into your watch window and make sure you have them all.
John wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 04-20-2006 12:26 PM
Hi I was having problems with the same thing but cant seem to get around it
i am trying to check against value in a database where the value is null when there is no match found


bool CheckEmail(string visEmail)
{
string strSql = "Select * from Visitors WHERE VisitorEmail = @visEmail";
SqlConnection objConnection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);

SqlCommand objCommand = new SqlCommand(strSql, objConnection);
objCommand.Parameters.Add("@visEmail", visEmail);

/*
SqlDataReader objDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection);
return objDataReader;
*/


objConnection.Open();


int result = 0;

try
{

result = (int)objCommand.ExecuteScalar();
}

finally
{
objConnection.Close();

}

if(result > 0)
{
return true;
}

else
{
return false;
}


}

this is the line giving me the problem:
result = (int)objCommand.ExecuteScalar();

thanks
Mark wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-08-2006 4:34 AM
Hi guys,

Just taken over hosting of a site giving this error when saving a form in their admin area. We're not an ASP house, so have no idea what's wrong, and the original developers are being unhelpful ;)

Anyway, this is the error:

[NullReferenceException: Object reference not set to an instance of an object.]
  Bovingdons.Admin.showcases.cmdMenuSaveChanges_OnClick(Object sender, EventArgs e)
  System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108
  System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57
  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
  System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
  System.Web.UI.Page.ProcessRequestMain() +1292



And this is the code for 'cmdMenuSaveChanges_OnClick':


protected void cmdMenuSaveChanges_OnClick(object sender, EventArgs e)
{
if   (selShowcaseMenu.Items.Count > 0)
{
if (selShowcaseMenu.SelectedItem.Text.IndexOf(" --- ") != -1)
{
// Section ITEM
selShowcaseMenu.SelectedItem.Text = " --- " + txtMenuItem.Text;
selShowcaseMenu.SelectedItem.Value = txtMenuItem.Text;
}
else
{
// Section
selShowcaseMenu.SelectedItem.Text = txtMenuItem.Text;
selShowcaseMenu.SelectedItem.Value = txtMenuItem.Text;
}

// hide/show buttons
cmdMenuSaveChanges.Visible = true;
cmdMenuSectionAdd.Visible = true;
cmdMenuSectionItemAdd.Visible = true;
cmdMenuItemRemove.Visible = false;
cmdMenuItemCancel.Visible = false;

txtMenuItem.Text = "";
selShowcaseMenu.SelectedIndex = -1;
}
}


Any help would be very, very welcome.  Thanks!
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-08-2006 9:49 AM
Mark,

Which line is throwing the error?  Have you stepped through it with the debugger?
Mark wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-08-2006 11:17 AM
Hi Raymond,

I have no idea which line is giving the error - no line is mentioned. I figured, since the error mentions 'cmdMenuSaveChanges_OnClick' that it would be that function that had a problem.

How do I use the debugger? (I am not familiar with ASP or .NET at all).

Thanks!
Mohammad Porooshani wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-10-2006 7:36 AM
Hi Raymond, I'm really confiused, I knew the Null reference exception even before reading your valuable article, but, I have a strange problem here:
I'm ading some data rows depending on user click on datagridview cells, it works well on adding the first row but, after adding the first one the Null reference exception occurs which I can't understand why!
I pass a datagridviewrow into a sub (in vb .net 2) and then extract some informatin and store them in a new datarow and then I add this new datrow into my dataset which binds to my datagridview (another gridview), as I told you, after first adding sequence it will throw null reference exception!
here is some codes:
Sub addToListSub(ByVal row As DataGridViewRow)
           Try
               Dim nerow As Data.DataRow = sDs.Tables("game").NewRow
               nerow(0) = row.Cells(1).Value
               nerow(1) = row.Cells(2).Value
               nerow(2) = row.Cells(3).Value
               nerow(3) = row.Cells(4).Value
               nerow(4) = row.Cells(5).Value
               MsgBox(sDs.Tables("game").TableName)
               sDs.Tables("game").Rows.Add(nerow)
           Catch ex As Exception
               MsgBox(ex.ToString)
           End Try
end sub

where sDs is a dataset.
Thank you in advanced,
Mohammad
Mohammad Porooshani wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-10-2006 7:46 AM
Oh, I forgot to say the exception returns the line where I add the row to dataset : sDs.Tables("game").Rows.Add(nerow)
thank you again,
Mohammad
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-10-2006 8:58 AM
Mark, read up on Using the Debugger in Visual Studio help.
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-10-2006 11:39 AM
Mohammad,

To be honest, I'm not really sure what's going on there.  I definately step through it and make sure that all your objects are still valid when you get to that line.  Pop sDs.Tables("games") into your watch window too to make sure its still valid.  Just looking at your code snippet, I'm not sure what's causing your problem.
Mohammad Porooshani wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-13-2006 3:50 AM
Thanks Raymond,
I'm sorry for my delay I was in holidays,
You know, I checked out all objects and I'm sure all of them exist in this line,
the thing that is really strange is that I checked my sDs and Found that the new row has been added to the sDs.tables(""game)!!!
but, my DataGridView wont show this lines (the null reference exception sill exists),
the most strange thing is that each time I try to do so (adding new rows after first row) they had been added but won't show up in the gridview,
I'm totally confused, would you help me?
Thank you in advanced.
Mohammad Porooshani
Mohammad Porooshani wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-13-2006 5:08 AM
Well, I checked it the way you wanted,
I added my sDs.tables("game") into watch list, but you won't believe it! it was exist! the problem is by "row" which I passed into the sub (I think).
it's still confusing because exactly at the start of the line which adds rows into dataset, everything is ok (I watched the "row" and found that it has a value of 1 or zero in red font which I think it's showing not allowed) but, immediately after executing this line (the line that throw the exception) everything is disappeared, sDs, nerow are disposed (it maybe OK because they are Autos in my "try" block) but the "row" still exist full of errors!
errors are all the same and is :error : Cannot Obtain Value!
so, I think the problem is for this reason, but I still can not find the solution as I tried to dispose the row to let it change but no answer yet.
Many thanks for your time for reading and please help!
Mohammad Porooshani
neptune7678 wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-16-2006 11:12 AM
4th common reason or 1st stoopid one...

the same error message is presented for all ASPX pages when the framework is installed but not registered with IIS

http://forums.asp.net/thread/1251988.aspx

went ahead and tested this out for ya (doh!)

what's really sad is that i had the same problem when setting up webservices on a different server; maybe i should go back to Java/Tomcat...

havagood1

Russ wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-16-2006 4:31 PM
None
Jignasa wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-20-2006 6:49 AM
I get System.NullReferenceException: Object reference not set to an instance of an object. in vb.net
my code is below plz give me the solution
=============================================
[NullReferenceException: Object reference not set to an instance of an object.]
  misforit.ser_msggrpcr.BindDataGrid() in E:\misforit\ser_msggrpcr.aspx.vb:111
  misforit.ser_msggrpcr.Page_Load(Object sender, EventArgs e) in E:\misforit\ser_msggrpcr.aspx.vb:103
  System.Web.UI.Control.OnLoad(EventArgs e)
  System.Web.UI.Control.LoadRecursive()
  System.Web.UI.Page.ProcessRequestMain()
================================================
 =========code=============
 'to Display remarks
       Dim objds As New DataSet()
       Dim daSuppliers As New OleDb.OleDbDataAdapter("SELECT service_no FROM mis_service_master where service_no like '%" & ser_value & "%'", con)
       Dim daProducts As New OleDb.OleDbDataAdapter("SELECT service_no,rem_id,rem_date,rem_desc  FROM mis_remark_mst where service_no like '%" & ser_value & "%'", con)
       daSuppliers.Fill(objds, "mis_service_master")
       daProducts.Fill(objds, "mis_remark_mst")
       con.Close()
       objds.Relations.Add("SuppToProd", objds.Tables("mis_service_master").Columns("service_no"), objds.Tables("mis_remark_mst").Columns("service_no"))
       Datagrid2.DataSource = objds.Tables("MIS_SERVICE_MASTER").DefaultView
       DataBind()

       objds.Dispose()
       daSuppliers.Dispose()
       daProducts.Dispose()
       con.Close()


=============================================
Samir wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-25-2006 4:48 AM
Hi Raymond,

Here you are my problem:

I have Page1.aspx and Page2.aspx witch are using one FloraMasterPage.master.

Page1.aspx:


<%@ Page Language="VB" MasterPageFile="~/FloraMasterPage.master" Title="Page1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
   
   <div>
       <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
       <asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="Page2.aspx" />
   </div>
</asp:Content>

Page2.aspx:

<%@ Page Language="VB" MasterPageFile="~/FloraMasterPage.master" Title="Page1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<script runat="server">
   Protected Sub Page_Load(ByVal sender As Object, ByVal s As System.EventArgs)
       Dim FN As New TextBox
       FN = CType(PreviousPage.FindControl("TextBox1"), TextBox)
       Label1.Text = FN.Text
       
       
   End Sub
</script>

   <div>
       <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
   </div>
</asp:Content>

When I try to recive some info. from TextBox1 from Page1.aspx I get
this:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 7:          Dim FN As New TextBox
Line 8:          FN = CType(PreviousPage.FindControl("TextBox1"), TextBox)
Line 9:          Label1.Text = FN.Text
Line 10:        
Line 11:        


Source File: C:\Flora_Webbsite\Undersidor\Page2.aspx    Line: 9

Thank you for help,
Samir

Niyazi Toros wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-06-2006 8:24 AM
Mohammad! dıd you use the sDs.Tables.AcceptChanges after adding the row
Mohammad Porooshani wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-07-2006 4:41 AM
yes dear Niyazi, I tried it, stil thesmae exception!
Himadrish wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-08-2006 9:44 AM
Thanks for the hard work!

It solves one of our confusion and we do understand why this error comming when caslling usercontrol event.

All the best! keep the good work going.

Thanks,
Himadrish
deejay_001 wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-08-2006 3:19 PM
My problem is with this section of Code...

   String str = "Something";
           bool looking = true;
           Response.Write("Checking MAC<br />");
           int count = 0;
           using (StreamReader sr = new StreamReader(proc.StandardOutput.BaseStream))
           {
               while (looking)
               {
                   Response.Write("DOING SOMETHING<br />");
                   str = sr.ReadLine();
                   Response.Write("ONCE AGAIN, DOING SOMETHING ELSE<br />");
                   int i = str.IndexOf("MAC Address = ");
                   Response.Write("Just used Index of Method (or property)<br />");
                   if (str == null)
                   {
                       looking = false;
                   }
                   if (i != -1)
                   {
                       result = str.Substring(i + "mac address = ".Length);
                       looking = false;
                   }
                   count++;
                   Response.Write(count.ToString() + "<br />");
               }
           }
           Response.Write("Done Checking MAC<br />");

I read through and initialized str to "Something".  I've placed the Response.Write calls so that I can see where the problem lies.

I'm able to debug it and run it in Visual Web Developer 2005 Express Edition without any problems.  When I view it using IIS, It
never gets to the line of code that reads

Response.Write("Just used Index of Method (or property)<br />");

IIS reports Object Reference message and that's it. No tracing info.  Nothing in the logs (both Event logs or W3SVC logs).  
Any ideas?  Here's the full function...

   public string IP2Mac(string IP)
   {
       string result = "Not found";

       try
       {
           ProcessStartInfo psi = new ProcessStartInfo("C:\\WINDOWS\\system32\\nbtstat", " -A "+ IP);
           Process proc = new Process();
           psi.RedirectStandardInput = true;
           psi.RedirectStandardOutput = true;
           psi.RedirectStandardError = true;
           psi.CreateNoWindow= true;
           psi.UseShellExecute = false;
           proc.StartInfo = psi;
           proc.Start();
           proc.WaitForExit();
           
           StreamReader err = proc.StandardError;
           String str = "Something";
           bool looking = true;
           Response.Write("Checking MAC<br />");
           int count = 0;
           using (StreamReader sr = new StreamReader(proc.StandardOutput.BaseStream))
           {
               while (looking)
               {
                   Response.Write("DOING SOMETHING<br />");
                   str = sr.ReadLine();
                   Response.Write("ONCE AGAIN, DOING SOMETHING ELSE<br />");
                   int i = str.IndexOf("MAC Address = ");
                   Response.Write("Just used Index of Method (or property)<br />");
                   if (str == null)
                   {
                       looking = false;
                   }
                   if (i != -1)
                   {
                       result = str.Substring(i + "mac address = ".Length);
                       looking = false;
                   }
                   count++;
                   Response.Write(count.ToString() + "<br />");
               }
           }
           Response.Write("Done Checking MAC<br />");
       }
       catch (Exception err)
       {
           Response.Write(err.Message);
       }
       Response.Write("Returning NOW<br />\n");
       return result;
   }

   public string getLocalIP()
   {
       String myIPAddress = "Not Found";

       try
       {
           IPAddress localIPAddress = new IPAddress(Dns.GetHostEntry(Dns.GetHostName().ToString()).AddressList[0].Address);
           myIPAddress = localIPAddress.ToString();
       }
       catch (Exception e)
       {
           return e.ToString();
       }

       return myIPAddress;
   }

Thanks, D
suzy wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-17-2006 11:48 PM
i am getting the same type of error I tried your solutions with no hope
Private Sub butCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butCreate.Click
       'use data set dsAgent1 to connect to agent_info table
       'create a new row object for the agent_info table
       Dim rowNew As dsAgent1._TableRow
       rowNew = DsAgent1._Table.New_TableRow
       'add data to the row
       rowNew.AGTNM = txtAGTNM.Text
       rowNew.AGTAD1 = txtAGTAD1.Text
       rowNew.AGTAD2 = txtAGTAD2.Text
       rowNew.AGTCTY = txtAGTCTY.Text
       rowNew.AGTST = drpAGTST.SelectedItem.Text
       rowNew.AGTZIP = txtAGTZIP.Text
       rowNew.AGTPH = txtAGTPH.Text
       rowNew.AGTEM = txtAGTEM.Text
       rowNew.AGTFAX = txtAGTFAX.Text
       rowNew.AGTCN = txtAGTCN.Text
       'Add the row to the data set
       DsAgent1._Table.Add_TableRow(rowNew)
       Try
           'modify the database
           adptAgents.Update(DsAgent1)
           'show sucess
           Server.Transfer("AddUserName.aspx")
       Catch ex As Exception
           Server.Transfer("ErrorAgent.aspx")
       End Try

   End Sub
Stan wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-27-2006 3:23 PM
I get this error occasionally on a specific .aspx form.  To resolve I have to download the dll file to bin folder again.  It will work for a month or more and the error will occur and the page will not work again until the dll is downloaded.  The dll will be unchanged from the previous iteration, in fact no code changes are made to the application at all.  

If anyone has an idea it would be greeeeaaaaatly appreciated.
Thanks,
Stan@stanralphsystems.com
Zia wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-29-2006 5:43 AM
<%@ Page Language="VB" Debug="true" %>
<%@ import Namespace="System.Data.SqlClient" %>
<script runat="server">

   Dim conn As New SqlConnection("server=zia;database=northwind;trusted_connection=true")

   Sub BindDataGrid()
        Dim cmd As New SqlCommand("Select * From Items",conn)
        conn.Open()
        Dim reader AS SqlDataReader=cmd.ExecuteReader()
        dgItems.DataSource=reader
        dgItems.DataBind()
        conn.Close()
   End Sub

   Sub Page_Load
        If Not IsPostBack Then
            BindDataGrid()
        End If
   End Sub

   Sub DoItemEdit(sender As Object,e As DataGridCommandEventArgs)
        dgItems.EditItemIndex=e.Item.ItemIndex
        BindDataGrid()
   End Sub

   Sub DoItemCancel(sender As Object,e As DataGridCommandEventArgs)
        dgItems.EditItemIndex=-1
        BindDataGrid()
   End Sub

   Sub DoItemUpdate(sender As Object,e As DataGridCommandEventArgs)
        Dim tbQty As TextBox
        dim tbprice As TextBox
        tbQty=CType(e.Item.FindControl("tbqty"),TextBox)
        tbQty=CType(e.Item.FindControl("tbprice"),TextBox)
        Dim statement As String
        statement="Update Items Set qty=" & tbQty.Text & "," & tbprice.text & " Where Item='" & dgItems.DataKeys(e.Item.ItemIndex)  & "'"

        Dim cmd As New SqlCommand(statement,conn)
        conn.Open()
        cmd.ExecuteNonQuery()
        conn.Close()

        dgItems.EditItemIndex=-1
        BindDataGrid()
   End  Sub

</script>
<html>
<head>
</head>
<body>
   <form runat="server">
       <asp:datagrid id="dgItems" runat="server" OnCancelCommand="DoItemCancel" OnUpdateCommand="DoItemUpdate" OnEditCommand="DoItemEdit" DataKeyField="Item" AutoGenerateColumns="false">
           <Columns>
               <asp:BoundColumn DataField="Item" HeaderText="Item" ReadOnly="true" />
               <asp:TemplateColumn HeaderText="Quantity">
                   <ItemTemplate>
                       <%# Container.DataItem("qty") %>
                   </ItemTemplate>
                   <EditItemTemplate>
                       <asp:TextBox id="tbQuantity" runat="server" Text='<%# Container.DataItem("qty") %>' />
                   </EditItemTemplate>
               </asp:TemplateColumn>
               <asp:Templatecolumn HeaderText="Unit Price">
                                   <ItemTemplate>
                                                 <%# Container.DataItem("unit_price") %>
                                   </ItemTemplate>
                                   <EditItemTemplate>
                                                     <asp:TextBox id="tbprice" runat=server Text='<%# Container.DataItem("unit_price") %>' />
                                   </EditItemTemplate>
               </asp:TemplateColumn>
                   <asp:EditCommandColumn EditText="Edit" UpdateText="Update" CancelText="Cancel" HeaderText="Edit Command Column" />

           </Columns>
       </asp:datagrid>
   </form>
</body>
</html>
///////////////////////////////////////////////////////////////////////
its have the following error mes can any one solove this...
thank
zia...
Koen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-03-2006 4:40 AM
I have a error: "Object reference not set to an instance of an object. " too, but i don`t know how i can get it out...

Can anybody help me please??
selvakumar wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-14-2006 10:21 AM
i have developed vb.net application. this application i am running in some other system. in this system only dot net frame work 1.1 only installed.In this application included vsflexgrdi thiry party component. in flex grid at runtime loaded combo box each row. so if i select the particular row combo box .it is throwing an runtime error "obejct reference not set to instance" so how to solve the problem.pls mail me.
my mailid :selva_mca04@yahoo.co.in
epoch wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-16-2006 11:23 PM
Im encountering the same problemm with my code:

'Processes To Write To Text File
       Dim SQLDA As SqlDataAdapter
       Dim dsDepartment As New DataSet


       dsDepartment = DSDBranch()

       Dim DepartmentCount As Integer
       Dim strBranch As String

       Dim TotalEPF As Double
       Dim TotalSocso As Double

       If dsDepartment.Tables("Branch").Rows.Count > 0 Then
           For DepartmentCount = 0 To dsDepartment.Tables("Branch").Rows.Count - 1

               strBranch = Trim(dsDepartment.Tables("Branch").Rows(DepartmentCount).Item("cbranch"))
               dsSalary = New DataSet
               dsSocso = New DataSet
               dsEPF = New DataSet
               dsEPFCR = New DataSet
               dsSocsoCR = New DataSet


               'Get information
               dsSalary = DSPayRoll("Salary", strBranch)
               dsSocso = DSPayRoll("Socso", strBranch)
               dsEPF = DSPayRoll("EPF", strBranch)
               dsEPFCR = EPFCRAccount(strBranch)
               dsSocsoCR = SocsoCRAccount(strBranch)


               'Write To Text

               TotalEPF = FileWriter.FileWriter(dsSalary, strBranch, "Salary")

               TotalSocso = FileWriter.FileWriter(dsSocso, strBranch, "Socso")
               FileWriter.FileWriterCR(dsSocsoCR, TotalSocso, strBranch, "Socso")

               TotalEPF = FileWriter.FileWriter(dsEPF, strBranch, "EPF")
               FileWriter.FileWriterCR(dsEPFCR, TotalEPF, strBranch, "EPF")

               

           Next

               lblInfor.Text = " Export Complete "
               MsgBox("Complete")
       Else

       End If

Especially at the 'Write to text' part.. could anyone pls help?
Sonalika wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-18-2006 5:08 AM
Please help me out in my application, there is a problem in the Object referencing that is showing in the MSFlexGrid, bieng used in the VB.net
the error is:

An unhandled exception of type 'System.NullReferenceException' occurred in Project1.exe

Additional information: Object reference not set to an instance of an object.

and the place he error is occurring is:


Public Sub Grid1()
       Dim j As Object
       Dim i As Object
       Dim z As Short
       Dim n As Short
       Dim mname As String
       mname = Trim(txt_mod_nam.Text)
       Frame2.Visible = True
       rs3 = con.Execute("select Part_type,Part_name from tbl_models where Model_name ='" & mname & "' order by Part_type")
       rs3.MoveFirst()
       z = 0
       While Not rs3.EOF
           z = z + 1
           rs3.MoveNext()
       End While
       MSHFlexGrid1.Rows = z
       MSHFlexGrid1.set_Cols(, 3)
Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-18-2006 1:37 PM
The best advice I can give you all is to step through and debug your code.  Each line you step into, check the objects on that page using your locals window or your watch window.  Make sure that the values are not null or nothing when you don't expect them to be.  That is the best approach for solving your issues.  I've only given you common scenarios, and most likely scenarios that apply to your situations.  Using the debugger will answer your questions and help you solve your problems.
S wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-20-2006 4:57 AM
Thanx for ur advice, i also used that but still the problem persists n my dead line for the project is near please help me to solve this problem the error is in the "

MSHFlexGrid1.Rows = z
line please checkthis out
Sonalika wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-20-2006 4:58 AM
Thanx for ur advice, i also used that but still the problem persists n my dead line for the project is near please help me to solve this problem the error is in the "

MSHFlexGrid1.Rows = z
line please checkthis out

thans dear
Sonalika wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-24-2006 8:08 AM
Hi!!
Can Any1 tel me what files are required for the windows Installer n what is the sequence of it?
Sonalika wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-24-2006 8:13 AM
basically for the VB.net deployment, and also windows Application
Niyazi Toros wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-26-2006 12:30 PM
Hi Mohammed,

Did you find solution to your problem?

recently I get same error in VB.NET. And I realize that my rows was over 45000 so I split to my rows into 2 datatable. Once I find the row then I add them the newly created 2th dataTable. Expect I checked each row before adding.

Examples:

  'CREATE A NEW DATATABLE AS FOLLOWS
          Try

               'I created new dataTable
'And the I add the 5 columns
       'Each columns I set the dataType as System.String
'And the last column I set as System.Decimal


          Catch ex As Exception
              MsgBox(ex.ToString)
          End Try


          Try
Dim xRow as DataRow
For Each xRow In myTable1.Rows

Dim mValue1 as Object
Dim mValue2 as Object
Dim mValue3 as Object
Dim mValue4 as Object
Dim mValue5 as Object

mValue1 = xRow(0)

'I checked each value to see if the data is DBNull or "" etc
'then I change the mValue1 to the value to see in my new table
'Once all value from 1 to 5 is set correctly
'then I add them into new DataTable

              Dim nerow As Data.DataRow = sDs.Tables("game").NewRow
              nerow(0) = mValue1
              nerow(1) = mValue2  
              nerow(2) = mValue3
              nerow(3) = mValue4
              nerow(4) = mValue5  
sDs.Tables("game").Rows.Add(nerow)

'Then I used the AcceptChanges before I checked if the newrow
'does not contains any error with HasError property.

Next
           
          Catch ex As Exception
              MsgBox(ex.ToString)
          End Try

Now everythings worked correctly. I hope you did the similar.

Rgds,
Niyazi
Ravi Dumka wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-02-2006 9:13 AM
i m having problem in th insert command .when we insert the data through form then it give the error Object reference not set to an instance of an object.

code iss
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
       Dim cmdinsert As New OracleCommand
       Dim bank As String = Session("bank_val")
       Dim off As String = Session("off")
       If Session("entry") = "1" Then
           'new entry
           'Dim insertcommand As New OracleCommand
           'insertcommand.Connection = con1.openconn()
           Dim query As String
           Dim empcl As Integer = Session("empcl")
           Dim tre_code As String= Session("ucode")
           Dim opcode As String = Session("opcode")
           Dim scal As String = Session("scal")
           Dim sextype As String = rblsex.SelectedItem.Value
           Dim pertemp As String = rblper.SelectedItem.Value
           query = "insert into emp_mast (trea_code,op_code,emp_code,pemp_code,emp_name,s_f_name,emp_qual,addr1,addr2,addr3,sex,per_tmp,scal_code,off_code,bill_code,empl_code,empt_code,desg_code,married,bankcode,ac_no,d_o_b,d_o_j,conf_date,inc_due_on,inc_stat,gpf_no,gpf_stat,pli_no,pan_no,delete_flag,ent_date,proc_flag,cadre,gpf_epf,rd_no,caste,tax_fin,nom_form_no,lic_pol_no1,lic_pol_no2,lic_pol_no3,lic_pol_no4,lic_pol_no5,lic_pol_no6,nominee) values('" & tre_code & "','" & opcode & "','" & txtempcode.Text & "','" & txtempcode.Text & "','" & txtempname.Text & "','" & txtfhname.Text & "','" & txtqual.Text & "','" & txtaddr1.Text & "','" & txtaddr2.Text & "','" & txtaddr3.Text & "','" & sextype & "','" & pertemp & "'," & scal & ",'" & off & "'," & txtscode.Text & "," & empcl & "," & ser_val & "," & txtdivcode.Text & ",'" & rblmrd.SelectedItem.Value & "','" & bank & "','" & txtacno.Text & "','" & tb_dob.Text & "','" & tb_doj.Text & "','" & txtcd.Text & "', '" & txtido.Text & "','" & rblic.SelectedItem.Value & "', '" & txtgpfno.Text & "', '" & rblgpfstat.SelectedItem.Value & "','" & txtpno.Text & "', '" & txtpanno.Text & "','0','" & System.DateTime.Now.ToShortDateString & "','0', '" & txtcadre.Text & "','" & tb_epf_gpf.Text & "','" & txtrdno.Text & "'," & txtcaste.Text & ", " & txtfy.Text & ", '" & txtnomfno.Text & "', '" & txtlc1.Text & "','" & txtlc2.Text & "','" & txtlc3.Text & "','" & txtlc4.Text & "','" & txtlc5.Text & "','" & txtlc6.Text & "','" & txtnominee.Text & "')"
           cmdinsert.CommandText = query

           cmdinsert.Connection = con1.openconn()
           cmdinsert.ExecuteNonQuery()
           con1.closeconn()
       Else
           'update entry

       End If
   End Sub
so plz help me immediately
Jeroen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-14-2006 8:01 AM
Thanks for the extensive explanations. It helped me with some code. But with this bit, it seems nothing helps:

Public Class cWinkelMandje
   dim alInhoud as New ArrayList()
   dim sItem as string
   dim sCart as String
   dim item as String
   dim alSession as new Arraylist()

   function addInhoud(byval sItem as String)
       alInhoud.add(sItem)
   end function

   function toonMandje() as String
       sCart = "Inhoud winkelwagen:<br>"
       for each item in alInhoud
           sCart = sCart & item & "<br>"
       next
       return sCart
   End function

   function setSession() as ArrayList
       return alInhoud
   end function

   function setInhoud(alSession)
       alInhoud = alSession
   end function
End class

Coudl you please point me in the right direction?
marky wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-23-2006 12:05 AM
hey,
need help i get this error from time to time when i click my save button.

Object reference not set to an instance of an object.
[NullReferenceException: Object reference not set to an instance of an object.]
  aprnet.WebForm1.SaveInvoice() in C:\My Project\aprnet\entry_invoice.aspx.cs:452
  aprnet.WebForm1.btnAddNew_Click(Object sender, EventArgs e) in C:\My Project\aprnet\entry_invoice.aspx.cs:583
  System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108
  System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57
  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
  System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
  System.Web.UI.Page.ProcessRequestMain() +1292

the odd thing is that i only get this error on our server which is windows 2003 but on my development computer using xp i dont get this problem. Unfortunately i cant debug it on our server (2003) and the problem does not exist on my development pc (xp). Are there known issue about this?

if it would help here's some part of the code.

private void SaveInvoice(){
double pfreight = 0;
if(txtPremiumFreight.Text!=""){
pfreight=Convert.ToDouble(txtPremiumFreight.Text);
}
dbInvoice dbinv = new dbInvoice();
int result = dbinv.AddInvoice(cboPONumber.SelectedValue,
Convert.ToInt32(cboRelease.SelectedValue),txtInvoice.Text.Trim()
,Convert.ToDateTime(txtInvDate.Text)
,Convert.ToDateTime(txtForwarderDate.Text)
,txtDockDate.Text
,Convert.ToDateTime(txtReceivingDate.Text)
,txtReceivedBy.Text,pfreight
,txtPFReference.Text,txtRemarks.Text,
User.Identity.Name,chkOriginal.Checked);
if(result>0){
LoadInvoices();
cboInvoice.Items.FindByValue(txtInvoice.Text).Selected=true;
ViewInvoiceData(cboInvoice.SelectedItem.Value);
}

please help me... thanx in advance.
marky
hrubesh wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-25-2006 2:55 AM

Hi , its been quite almost one week now i'm stuck on a object reference not set to an instance of an object problem. i cannot post u the code it is useless, I need to mail u the project itself and i need a mail add of yours.

Problem: i have a custom datagridview . then i put in on a usercontrol (Drag n drop) ,.  then i drag drop usercontrol on a form.,

when i try access properties of the datagrid, i get object reference... message at design time.

thanking you beforehand,

hrubesh

daffodil wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-25-2006 2:21 PM

ERROR:  'Object reference not set to an instance of an object'

I have this error coming up always ever since i've written one statemnt to use sessions and it is the following,

Dim userselection As String

If (Session("selection") Is Not nothing) Then

userselection = Session("selection").ToString()

End If

Public Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles DataGrid1.ItemDataBound

       Dim userselection As String = Session("selection").ToString()

       Session.Add("selection", "info1")

       If (userselection = "info1") Then

           DataGrid1.Columns(3).Visible = False

           DataGrid1.Columns(4).Visible = False

           DataGrid1.Columns(5).Visible = False

           DataGrid1.Columns(6).Visible = False

           DataGrid1.Columns(7).Visible = False

       end if

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

       Session.Add("selection", "info1")

End Sub

Can someone tell me if my initialization for the null string in vb.net is wrong??

Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-30-2006 2:45 PM

hrubesh,

Use the Contact link above to send me email.

Dark Otakon wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-11-2006 8:00 PM

My problem is the following one:  I have an application with a menu screen, in the menu selects the screen to execute. Some times it happens that I leave some screen and an error is sent (Unhandled Exception: "NullReferenceException Object reference not set an instance of an object"), but most of the times is not sent, leaving the same screen. The problem is that a pattern does not exist to reproduce the error, the error does not happen in time of development. I am using WinForms also customized controls in VS 2003: VB .NET

I thank for the commentaries or the aids that can give me.

elitehunter99 wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-12-2006 10:04 AM

I am having the same problem, here is the error message in the event viewer for the application "WorkStationUsage".

Description:

Service cannot be started. System.NullReferenceException: Object reference not set to an instance of an object.

  at PramodSingh.LibPOP3.POP3.SaveAttachments(Int32 MsgNumber, String dirPath)

  at WorkStation.WorkStationUsage.DoOperationCycle()

  at WorkStation.WorkStationUsage.OnStart(String[] args)

  at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)

I have the following object defined:

namespace WorkStation

{

public class WorkStationUsage : System.ServiceProcess.ServiceBase

{

private PramodSingh.LibPOP3.POP3 Pop3Client;

            }

protected void DoOperationCycle()

{

timer.Stop();

//Pop3Client.Reset();

try

{

this.Pop3Client = new PramodSingh.LibPOP3.POP3("countei","c0unter1nf0","YYZ-EXCH01.YYZ.GTAA",false);

this.Pop3Client.Open();

}

catch (Exception e85)

{

eventLog.WriteEntry("Error: " + e85.Message, System.Diagnostics.EventLogEntryType.Error);

}

int msgNumber = this.Pop3Client.NumOfMessages - 1;

this.Pop3Client.SaveAttachments(5, "U:\\Program Files\\");

timer.Start();

}

}

I have included the LibPOP3.dll file as a Reference in the Project, but I am still getting the NullReferenceException when trying to use a method from the POP3 class. Any ideas are greatly appreciated, plz email back at elitehunter@gmail.com

mk wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-12-2006 1:54 PM

Hi, i've been encountering same problem. NullReferenceException: Object reference not set to an instance of an object.

this App is in production, and users are often getting this error.

my problem is i'm not able to reproduce error from development environment. Can i send code and stack trace of error to You?         Thank you very much

Melissa wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-18-2006 1:16 PM

Please Help. I have been getting the Object reference not set to an instance of an object error. I have no idea what could be causing this problem. I completed a tutorial from the c# bible and I get the same error. Do you have a few minutes to look at my code?

Dark Otakon wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-18-2006 5:35 PM

This is the exception message, I can't find the error in the application

System.NullReferenceException: Object reference not set to an instance of an object.

  at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)

  at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)

  at System.Windows.Forms.Control.DefWndProc(Message& m)

  at System.Windows.Forms.Control.WmUpdateUIState(Message& m)

  at System.Windows.Forms.Control.WndProc(Message& m)

  at System.Windows.Forms.ScrollableControl.WndProc(Message& m)

  at System.Windows.Forms.ContainerControl.WndProc(Message& m)

  at System.Windows.Forms.ParkingWindow.WndProc(Message& m)

  at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)

  at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)

  at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Please, I need help!!

Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-18-2006 9:30 PM

I really wish I had time to look at everybody's code and help you figure out what it going on.  I get many, many emails a day, believe it or not, from people asking me for the same thing.  My best answer to you all is to set a breakpoint where the code is throwing the error, step through the code with the debugger, and find out which piece is set to null/nothing when you are expecting it to be something.  If you need help understanding this concept of breakpoint, debugging and using your locals and watch windows, please let me know and I will post an article regarding such.

hossman wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-25-2006 4:26 AM

getting the same error here:

dim points1 as integer

row = DataSet1.Batsmen.NewBatsmenRow

row = DataSet1.Tables("Batsmen").Rows.Find(Batsman1.SelectedValue)

points1 = row.Item("Points")

vijay kumar wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-05-2006 7:45 AM

hi sir,

      i want sent value in datadase from dropdownlist (htmlcontrol),but i m falure so plez help me

Phillip Turner wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-13-2006 3:28 PM

MSDN MSDN.  Looks like everyone wants poor old Ray to fix their issues.  Suck it up and read a book people.

marky wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-16-2006 2:02 AM

hey I'll repost my post up... im still having this problem with windows2003 server but xp doesnt encounter this problem. need help i get this error from time to time when i click my save button.

the odd thing is that i only get this error on our server which is windows 2003 but on my development computer using xp i dont get this problem. Unfortunately i cant debug it on our server (2003) and the problem does not exist on my development pc (xp). Are there known issue about this? can you please send it to logger1216@yahoo.com if u can help me. thanx

Object reference not set to an instance of an object.

[NullReferenceException: Object reference not set to an instance of an object.]

 aprnet.WebForm1.SaveInvoice() in C:\My Project\aprnet\entry_invoice.aspx.cs:452

 aprnet.WebForm1.btnAddNew_Click(Object sender, EventArgs e) in C:\My Project\aprnet\entry_invoice.aspx.cs:583

 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +108

 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +57

 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18

 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33

 System.Web.UI.Page.ProcessRequestMain() +1292

if it would help here's some part of the code.

private void SaveInvoice(){

double pfreight = 0;

if(txtPremiumFreight.Text!=""){

pfreight=Convert.ToDouble(txtPremiumFreight.Text);

}

dbInvoice dbinv = new dbInvoice();

int result = dbinv.AddInvoice(cboPONumber.SelectedValue,

Convert.ToInt32(cboRelease.SelectedValue),txtInvoice.Text.Trim()

,Convert.ToDateTime(txtInvDate.Text)

,Convert.ToDateTime(txtForwarderDate.Text)

,txtDockDate.Text

,Convert.ToDateTime(txtReceivingDate.Text)

,txtReceivedBy.Text,pfreight

,txtPFReference.Text,txtRemarks.Text,

User.Identity.Name,chkOriginal.Checked);

if(result>0){

LoadInvoices();

cboInvoice.Items.FindByValue(txtInvoice.Text).Selected=true;

ViewInvoiceData(cboInvoice.SelectedItem.Value);

}

please help me... thanx in advance.

marky

Mike McDonald wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-16-2006 5:03 PM

Ray,

I get the following error when I try to log onto a website. Is this their problem or mine? Thanks

[NullReferenceException: Object reference not set to an instance of an object.]

  VOS.Index.GetMapViewJavascript() +59

  VOS.Index.Page_Load(Object sender, EventArgs e) +54

  System.Web.UI.Control.OnLoad(EventArgs e) +99

  System.Web.UI.Control.LoadRecursive() +47

  System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061

Ole Frederiksen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-24-2006 9:29 AM

Being quite new to .net I have tried making a webservice which get called from a C# application. The webservice seems to work fine (as I can test it with a positive result), but when using it from the C# application it fails with the NullReferenceException...

The webservice looks like this:

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

[WebService(Namespace = "http://www.myurl.dk/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Temperature : System.Web.Services.WebService

{

   private decimal decTemp; // placeholder for calculating temperature

   private string strTemp; // placeholder for string representation of temperature

   public Temperature () {

       //Uncomment the following line if using designed components

       //InitializeComponent();

   }

   [WebMethod(Description = "Converts Fahrenheit to Celcius or vice versa. c2f means C. to F. f2c means F to C.")]

   public string Convert(string fromTo, double temperature) {

       if (fromTo == "c2f")

           decTemp = ((decimal)temperature * 1.8m) + 32;

       else

           decTemp = ((decimal)temperature - 32) * (5m / 9m);

       strTemp = "32";//decTemp.ToString("0.0", null);

       return strTemp;

   }

}

And the C# application looks like this:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace ConvertTemperature

{

   public partial class Form1 : Form

   {

       public Form1()

       {

           InitializeComponent();

       }

       private localhost.Temperature remoteTemperature;

       private string result;

       private void Form1_Load(object sender, EventArgs e)

       {

           remoteTemperature = new localhost.Temperature();

       }

       private void convertButton_Click(object sender, EventArgs e)

       {

           if (fahrenheitRadioButton.Checked)

               result = remoteTemperature.Convert("f2c", Convert.ToDouble(temperatureTextBox.Text));

           else

               result = remoteTemperature.Convert("c2f", Convert.ToDouble(temperatureTextBox.Text));

           outputLabel.Text = result;

       }

   }

}

The c# app contains a few controls:

Textbox: temperatureTextBox

RadioButton: fahrenheitRadioButton

RadioButton: celciusRadioButton

Button: convertButton and

Label: outputLabel

The exception happens when trying to call the webservice

Thanks for all the help I can get here.

/Ole

Dmitri wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-05-2006 6:54 PM

Hi Raymond,

I have the same problem as Nelson - "Object reference not set to an instance of an object error" on an application that runs fine for a few days and then this error happens. I then have to go kill the aspnet_wp.exe process to get the application to work again. I talked to ActivePdf support and they sent me this link. The code is below, and thanks in advance

using APToolkitNET;

APToolkitNET.Toolkit TK = new APToolkitNET.Toolkit();

long r = TK.OpenInputFile(pdfTemplateFile);

Neal wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-09-2006 12:57 PM

Hey

im having this error in an assignment but its appearance is random, some times my program will loop x amount of times and be fine and other times it will crash on the 2nd loop. I'm a beginner programmer at university. If any one has msn messenger and could add me either later today or tomorrow that wud be great, any later and it will be to late cos the assignment is in on monday.

z3r0n3rd69@hotmail.com

Dcoder wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-14-2006 5:46 AM

DataSet ds_CustomerOrder = getCustOrder(custInFocus);

this.dgCustomerOrder.DataSource = ds_CustomerOrder.Tables["Data"];

dgCustomerOrder.Columns[0].Width = 0;

this.dgCustomerOrder.Columns[0].Resizable = DataGridViewTriState.False;

the line "dgCustomerOrder.Columns[0].Width = 0;" causes the nullreferenceexception.

ds_CustomerOrder is a valid dataset containing 2 rows of data.

Confused :S:S

Scott’s Blog » Common causes of the System.NullReference exception wrote Scott&#8217;s Blog &raquo; Common causes of the System.NullReference exception
on 01-01-2007 10:36 AM
ramprasad wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 01-05-2007 1:51 PM

Im getting the error for the following code. the error is  "System.NullReferenceException: Object reference not set to an instance of an object."        

HyperLink[] hyp = new HyperLink[10];

       hyp[0].Text = "hello";

       hyp[0].NavigateUrl = "http://www.google.com";

       Controls.Add(hyp[0]);

please help me out.

Hari wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 01-16-2007 4:18 AM

help me for completing datagridpaging

Crystalite Imran wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 01-16-2007 9:00 PM

Hi Raymond,

Im new in VB.ET and I'm not sure how to use the debugger. Since you have mentioned that you are able to post it out, why not!

Thanks in advance! ;)

Pallavi wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 01-20-2007 5:54 AM

I am getting this error:System.NullReferenceException: Object reference not set to an instance of an object. while running my form in deployment site

Sahani Said: wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 01-23-2007 5:35 AM

[NullReferenceException.Object reference not set to an instance of an object]

Scopes.Web.Quote.wfrmQuotedetails.PageLoad(Object sender, EventArgs e) +151

System.Web.UI.Control.Onload(EventArgs e) +67

System.Web.UI.Control.LoadRecursive() +35

System.Web.UI.Page.ProcessRequestMain() +750

Laury Burr wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-03-2007 6:50 AM

I'm getting the same dreaded "Object reference not set" message, but in my case it's from the parser - the page doesn't even load.

The parser identifies the error on the line specifying the first "column" within a GridView in dotNet 2.0.

<asp: CommandField ShowSelectButton="True" ButtonType="Button" SelectText="Select" />

Even though on the codebehind page I've declared the GridView object itself:

   Protected WithEvents Grid1 As System.Web.UI.WebControls.GridView

And there I was thinking that moving from VBA to .NET would be easy (well, not this frustrating, anyway!)

venkatesh wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 03-07-2007 4:52 AM

I am using c# 2003, i am getting Object reference not set to an instance of an object, when i run my code. I am trying to delete a record through my aspx page, but i get this Object reference message,. But when i see in the database, the data is actually deleted. whats happening? Why is this error appearing?

Sonia wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 03-18-2007 1:48 AM

Hi,

Iam getting this error:

System.NullReferenceException: Object reference not set to an instance of an object.

Line 183:        With objFlowMapBasicDO

Line 184:            .sName = txtName.Text

Line 185:            .sDescription = txtDescription.Text

Line 186:            .sTitle = txtTitle.Text

thanx

FuQ2 wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 04-05-2007 6:41 PM

Look at this...all questions and not a single answer

This blog is crap.

I shit on your site

Raymond Lewallen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 04-05-2007 6:55 PM

FuQ2,

Usually I delete comments from cowards like you who can't identify themselves because your loser factor extends beyond what most people are able to comprehend.  But thanks for stopping by.  People always like to see that no matter how bad they feel or how bad times are, at least they aren't you, and it makes them happy again.  Many people will enjoy your comment.

This is not a question and answer forum.  This is a blog.  If people, such as yourself, actually took time to read the comments, you would see that I've stated that I am not answering questions on this post.

From above:

"  

rlewallen said:

I really wish I had time to look at everybody's code and help you figure out what it going on.  I get many, many emails a day, believe it or not, from people asking me for the same thing.  My best answer to you all is to set a breakpoint where the code is throwing the error, step through the code with the debugger, and find out which piece is set to null/nothing when you are expecting it to be something.  If you need help understanding this concept of breakpoint, debugging and using your locals and watch windows, please let me know and I will post an article regarding such."

rty wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-03-2007 7:46 AM

project wroks properly on my localhost but when I upload on Clients server it gives an error:Object reference not set to an instance of an object.

Tom Ng wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-25-2007 4:43 PM

Hi,

I need help!! I have this error when I am using ajax.net to modify a cell on a grid and when i do a post back it gives me this error.  I step through the code but the error occurs at the end of a function.  therefore i do not know what causes it.

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]

  Infragistics.WebUI.UltraWebGrid.UltraWebGrid.ProcessChanges(StateChanges stateChanges, Boolean fireEvents) +6888

  Infragistics.WebUI.UltraWebGrid.UltraWebGrid.RaisePostDataChangedEvent() +126

  System.Web.UI.Page.RaiseChangedEvents() +137

  System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4778

Dhipak wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-11-2007 7:14 AM

Hi ....

I am getting the same error  BUT THE CATCH IS...THIS ERROR IS NO WHERE COMING UP IN THE RUNNING APPLICATION BUT IT IS COMING UP IN THE EVENT VIEWER.

PLZ HELP.....

THANKZ...

Fariborz wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-19-2007 5:23 AM

Just I wanted to say thank you for nice article.

praveen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-25-2007 1:25 AM

i am geeting a problem in C#.net as follows

While i am entering seme number in a text box

if I press a button it shows previous record.

i want the code ;

i am using backend as MSAccess Database

praveen wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-25-2007 1:28 AM

i want te code for geeting next record from the table .in a database wit msccess database

Haripriya wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-25-2007 5:20 AM

Nice Article

Haripriya wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-25-2007 5:22 AM

Nice Article

Saby wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-26-2007 7:23 PM

I am getting the same error . The scenario is that I have 2 combo boxes and on selecting a value in one combo , I have to populate the values in the other combo box. I have written the code under the SelectedIndexChanged() method.

The code where the exception occurs is where I try to get the selected value .

string selectedBrand = brandNameComboBox.SelectedValue.ToString();

Help me.

Judylj60 wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-28-2007 6:42 AM

Why would this error occur on one machine but not another with the same code?  I developed the application on my laptop and it runs great.  I sent it to my instructor and she gets this error.  I downloaded the same files I sent to my instructor to my work computer and it runs great.  I don't get it.

Arun Ashok wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-14-2007 5:00 AM

i am getting this error while i load values from grid to combo. to load values in the combo i am using dll's which are created by compiling class file.load combo item data function is written inside the class file which is compiled in to dll.the program with this dll is working gr8 in the developers machine and shows error in  client machine.i deployed all the dependencies in the client machine but error is still there.yeah the error is not constant.sometimes itz works gr8 in client machine and sometimes not.can u tell me why itz happening.i am terribly desperate.please help me to get out of this Bermuda triangle.please

Jeff wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-19-2007 3:43 PM

I am working on a code for work with this Visual Basic line producing an error when viewed in a browser:

Dim tracking As TazTracking = New TazTracking(Session("user"))

the warning:

Variable 't' is used before it has been assigned a value. A null reference exception could result at runtime.

How can I declare this type without error?

Patrick Smacchia wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-19-2007 4:10 PM
The ultimate weapon to avoid NullReferenceException lie in non-nullable type: http://blogs.msdn.com/cyrusn/archive/2005/04/25/411617.aspx Unfortunatly there is few chances that it will ever be integrated to C#. I would say that 70% or even more references are actually non-nullable. Introducing non-nullable type would then provoke major refactoring.
Peter wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-29-2007 4:04 PM

Ray,

I have an issue here in this code:

   Private Sub ddlSchool_collegeName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlSchool_collegeName.SelectedIndexChanged

       Dim sqlStr As String

       ddlDomesticInternational.Items.Clear()

       ddlInsuranceCompany.Items.Clear()

       txtPolicyNumber.Text = ""

       ddlStudentClassification.Items.Clear()

       ddlCoveragetype.Items.Clear()

       ddlEnrollmentTerm.Items.Clear()

       txtDateOfCoverageFrom.Text = ""

       txtDateOfCoverageTo.Text = ""

       sqlStr = "select distinct domestic_international from enrollment_coverage_info where college_university_name ='" & Trim(ddlSchool_collegeName.SelectedItem.Text) & "'"

       ddlDomesticInternational = ExecuteCommand(ddlDomesticInternational, sqlStr)

       txtPolicyNumber.Text = ""

   End Sub

The error is:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]

  ajf.Admin_Student_Waiver_From.ddlSchool_collegeName_SelectedIndexChanged(Object sender, EventArgs e) in C:\Inetpub\wwwroot\ajf\Admin\Admin_Student_Waiver_From.aspx.vb:150

  System.Web.UI.WebControls.ListControl.OnSelectedIndexChanged(EventArgs e) +108

  System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() +26

  System.Web.UI.Page.RaiseChangedEvents() +115

  System.Web.UI.Page.ProcessRequestMain() +1099

I can't for the life of me figure this out... Please email me at: peter@webparity.net and I'll send you login info to assist. PLEASE!

Thanks

Byron wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-23-2007 8:50 PM

I'm receiving the error System.NullReferenceException - Object reference not set to an instance of an object.  Here is the code that I wrote.  The website is displaying a photo album and I've provided a next and previous button.  I can view pics using next, and can view 1 pic backwards using the previous button.  But, on the second previous command I get the error.

Public Sub GetSelectedPhotoInfo()

       dtPagerPhotoInfo = CType(Session("dtPagerPhotoInfo"), DataTable)

       dtPagerPhotoInfo.DefaultView.RowFilter = "RecNo = '" & CType(ViewState("SelectedRecNo"), Integer) & "'"

       For Each oRowView As DataRowView In dtPagerPhotoInfo.DefaultView

           Dim FileName As String = oRowView("PhotoID").ToString & "." & oRowView("PhotoType").ToString

           imCurrentPhoto.ImageUrl = "~/PhotosFullSize/" & FileName

           lbPage.Text = "Photo " & ViewState("SelectedRecNo").ToString & " of " & ViewState("TotalRecs").ToString

           lbPhotoName.Text = oRowView("PhotoName").ToString

           hlFullSize.NavigateUrl = "ViewFullSize.aspx?FileName=" & FileName

           hlFullSize.Target = "blank"

       Next

       dtPagerPhotoInfo.Dispose()

       dtPagerPhotoInfo = Nothing

   End Sub

Back to BACK and INSERT again! « System.Errors + brickbats wrote Back to BACK and INSERT again! &laquo; System.Errors + brickbats
on 08-26-2007 2:09 PM

Pingback from  Back to BACK and INSERT again! &laquo; System.Errors + brickbats

solamudiyathu wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-19-2007 6:46 AM

Poda en ditch punaku

Sam Eng wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 09-24-2007 4:27 AM

Why everyone keep posting error no one help to solve??

Julio wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-10-2007 10:13 AM

Here is a good one for you.  I have code that works in the development environment but not in production.  The error in production is the NullReferenceException: Object reference not set to an instance of an object

mario wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-13-2007 10:58 AM

is this a computer problem or website?? is it my computer or i need to fix this??

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]

  Presentation.gateway.DisplayTopNav() +242

  Presentation.gateway.Page_Load(Object sender, EventArgs e) +847

  System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15

  System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +34

  System.Web.UI.Control.OnLoad(EventArgs e) +99

  SCShared.BasePage.OnLoad(EventArgs e) in C:\Inetpub\SCShared\BasePage.cs:733

  System.Web.UI.Control.LoadRecursive() +47

  System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061

jp.lyricbus.com wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-26-2007 3:10 AM

Good Article

李建伟 wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 11-16-2007 10:36 PM

看了看楼主说的,觉得挺好的,就是不是特别明白.........

Sohail raza wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 11-19-2007 7:32 AM

Hi, my name is Sohail Raza and i m student of M.Sc ( computer sciences )  in QAU  pakistan and i want to join ur forum plz tell me the procedure to have a free membership of this forum .thanks in advance.

Megan wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 11-22-2007 4:11 AM

I have problem with Application

"Server Error in '/' Application."

George wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 11-27-2007 6:30 AM

hi People!

BalaKumar.T.L. wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 11-28-2007 6:44 AM

Hi Raymond,

I need help!! I have this error therefore i do not know what causes it. Im new in VB.NET and I'm not sure how to use the debugger. Since you have mentioned that you are able to post it out, why not!

---------------------------------------------------------------------------------------

Server Error in '/SQLPGRS' Application.

--------------------------------------------------------------------------------

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 242:        SQry &= TxtPetitionerName.Text & "', '" & TmpAge & "', '"

Line 243:        SQry &= DdlGender.SelectedItem.Text & "', '" & StrAddress & "', '"

Line 244:        SQry &= TxtContactNo.Text & "', '" & DdlStationName.SelectedItem.Text & "', '"

Line 245:        SQry &= Me.TxtPetition.Text & "', '" & DdlSubject.SelectedItem.Text & "', '" & UStatus & "', "

Line 246:        SQry &= DdlConfidential.SelectedItem.Value & ",'Standard','" & Now & "')"

Source File: c:\inetpub\wwwroot\SQLPGRS\FrmPetitionEntry.aspx.vb    Line: 244

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]

  SQLPGRS.FrmPetitionEntry.BtnSave_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot\SQLPGRS\FrmPetitionEntry.aspx.vb:244

  System.Web.UI.WebControls.Button.OnClick(EventArgs e)

  System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)

  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)

  System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)

  System.Web.UI.Page.ProcessRequestMain()

--------------------------------------------------------------------------------

Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573

---------------------------------------------------

Thanks in advance! ;)

kral oyun wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 11-29-2007 4:07 AM

I am getting this error:System.NullReferenceException: Object reference not set to an instance of an object. while running my form in deployment site

Thanks

Jose Luis wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-06-2007 3:17 PM

Hi Raymond,

This is my situation, i am developing a web application in C# on the frame work 1.1.

I have two enviroments one is the development which is on a local server and the second is the testing server which is located at the testing server of the client.

When I am working in the development enviroment everything works fine but when the application is deployed into the testing server in one of the modules for an specific case it displays the following error :

System.NullReferenceException - Object reference not set to an instance of an object.

The strange thing is that if I run the web application from my pc to debug it on the testing server it works normally as if I were working on the local enviroment.

Do you have an idea of what is happening and how can I solve this problem?

Thanks in advance

Jose Luis wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-06-2007 3:22 PM

Hi Raymond,

This is my situation, i am developing a web application in C# on the frame work 1.1.

I have two enviroments one is the development which is on a local server and the second is the testing server which is located at the testing server of the client.

When I am working in the development enviroment everything works fine but when the application is deployed into the testing server in one of the modules for an specific case it displays the following error :

System.NullReferenceException - Object reference not set to an instance of an object.

The strange thing is that if I run the web application from my pc to debug it on the testing server it works normally as if I were working on the local enviroment.

Do you have an idea of what is happening and how can I solve this problem?

Thanks in advance

Fred C. wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-13-2007 2:27 PM

Raymond -

I am a novice VB.Net hobbyist, and am working on a project having two forms.

The first form has a label, and a button that shows the 2nd form on the click event.

While in the 2nd form, I am attempting to write data to the 1st form's label, however, I get the error

System.NullReferenceException - Object reference not set to an instance of an object.

When programming in VB6, I had no trouble referencing other forms in a project, but now....

Thanks for any tips you might have.

- Fred

Leonid wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-14-2007 12:29 AM

I have found a solution for this common problem.

First you identify the object that is producing this error with TRY and CATCH block.

Then place IF statement before you accessing this object as following:

If Not (YOUR_OBJECT Is Nothing) Then

Do your staff with this object…

End If

This way you avoid getting this anoying error for good.

youyuanfun wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 01-15-2008 10:08 AM

I have a windows service program to update SQL Server Database's data every night. It works fine in my Desktop PC. But when I move this program to a service server, I always get "object reference not set to an instance of an object" exception.

Is some one can help me to solve this problem?

Thanks a lot!

jugadee wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 01-16-2008 1:42 PM
For those of you who are experiencing the "object reference not set to instance of object" error only on your production servers when it does not occur on the development server, I reuploaded the web.config file to the production server and the error was resolved. I did not find that anything in the web.config had changed, but who know what's going on behind the scenes? I sure don't - with Microsoft so much is hidden to non-engineers.
DotNetKicks.com wrote 3 Common causes of System.NullReferenceException in VB.Net
on 01-23-2008 10:09 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Andrew wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 01-31-2008 5:15 PM
The second line of code throws a null reference expception, sometimes. I have run it in dev many times and stepped through the code and everything works fine. I deploy and it works fine, most of the time, but sometimes the second line below throws a null reference exception. ConnectionInfo connection = new CrystalDecisions.Shared.ConnectionInfo(); connection.ServerName = MainDSNName; Im using C# .NET 2.0 Any help?
Hiding wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-03-2008 4:35 PM
CSS ------ #nav li { display:block; float:left; position:relative; } /*To make the group links visible when hovered on them */ #nav li a span { display:block; float:left; height:22px; letter-spacing:1px; padding:9px 21px 0pt; } #nav ul { border-top:1px solid #FFFFFF; display:none; left:7px; margin:0pt; padding:0pt 0pt 6px; position:absolute; top:31px; width:160px; } #nav li:hover ul, #nav li.over ul { display:block; z-index:100; } #nav ul li a, #nav li:hover ul li a, #nav li.over ul li a { background:#B0B0B0 none repeat scroll 0%; border-bottom:1px solid #FFFFFF; display:block; padding:5px 0pt 3px 8px; width:132px; } CODE ---------
ahmed wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-19-2008 10:07 AM
i have received that error but when i am trying to trust assembly from ( Microsoft .NET Framework 1.1 Wizards )
Dread wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 03-12-2008 10:43 AM

God, this really is a great example of ignorance. You ppl really should try and learn the very basics of asp.net before you're starting to spam ppl that actually explain things. And second of all, learn to read. Raymond's already stated TWICE that he doesn't have time to answer all your questions (Really, did you _really_ think a person with the same amount of hours on his day had time to answer all of this? I mean, come on. Half of you can't explain, let alone grasp the very basics it seems.).

Take the advice added above and go buy a book about asp.net and start from there. That way you won't have to come here for the next error you get aswell.

To Raymond - Awesome article. Keep up the good job and /ignore the drones.

Ron Hyatt wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 04-10-2008 12:47 PM

So it appears I have to catch the exception if the object is null; no other way around it.

izat wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 04-22-2008 10:54 PM

Imports System.Data

Imports System.Data.SqlClient

Imports System.Web.Configuration

Partial Class AduanHeader_Default

   Inherits System.Web.UI.Page

   Public SQL As String

   Protected Sub btnHantar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHantar.Click

       If btnHantar.Text = "Simpan Data" Then

           If txtNoKadPengenalan.Text = "" Then

               Dim MyScript As String = "<SCRIPT language='javascript'>window.alert('Sila Masukkan No Kad Pengenalan.')</SCRIPT>"

               ClientScript.RegisterStartupScript(Me.GetType(), "ErrUser", MyScript)

               txtNoKadPengenalan.Focus()

           ElseIf txtNama.Text = "" Then

               Dim MyScript As String = "<SCRIPT language='javascript'>window.alert('Sila Masukkan Nama .')</SCRIPT>"

               ClientScript.RegisterStartupScript(Me.GetType(), "ErrUser", MyScript)

               txtNama.Focus()

           Else

               SimpanAduan()

               Dim MyScript As String = "<SCRIPT language='javascript'>window.alert('Data Telah Di simpan.')</SCRIPT>"

               ClientScript.RegisterStartupScript(Me.GetType(), "ErrSave", MyScript)

               txtNoKadPengenalan.Text = ""

               txtNama.Text = ""

           End If

       Else

           If txtNoKadPengenalan.Text = "" Then

               Dim MyScript As String = "<SCRIPT language='javascript'>window.alert('Sila Masukkan  No Kad Pengenalan.')</SCRIPT>"

               ClientScript.RegisterStartupScript(Me.GetType(), "ErrUser", MyScript)

               txtNoKadPengenalan.Focus()

           ElseIf txtNama.Text = "" Then

               Dim MyScript As String = "<SCRIPT language='javascript'>window.alert('Sila Masukkan Nama.')</SCRIPT>"

               ClientScript.RegisterStartupScript(Me.GetType(), "ErrUser", MyScript)

               txtNama.Focus()

               'Else

               ' KemaskiniAduan(lblAduan.Text)

               ' Dim MyScript As String = "<SCRIPT language='javascript'>window.alert('Data Telah Di simpan.')</SCRIPT>"

               'ClientScript.RegisterStartupScript(Me.GetType(), "ErrSave", MyScript)

               btnHantar.Text = "Simpan Data"

               txtNoKadPengenalan.Text = ""

               txtNama.Text = ""

           End If

       End If

   End Sub

   Protected Sub SimpanAduan()

       Dim sDB As String = ConfigurationManager.ConnectionStrings("AduanPelajar").ConnectionString

       Dim Conn As SqlConnection = New SqlConnection(sDB)

       Conn.Open()

       Try

           Dim SQL As SqlCommand = New SqlCommand

           SQL.CommandText = "INSERT Into ad_AduanHdr VALUES('" + txtIdAduan.Text + "','" + ddlKategori.SelectedValue + "','" + txtNoKadPengenalan.Text + "','" + txtNama.Text + "','" + _

 txtEmail.Text + "','" + txtNoTelefon.Text + "','" + txtNoHp.Text + "','" + txtAdd1.Text + "','" + txtAdd2.Text + "','" + _

 txtPoskod.Text + "','" + txtBandar.Text + "','" + ddlNegeri.SelectedValue + "','" + ddlNegara.SelectedValue + "','" + txtTajuk.Text + "','" + _

 txtAduanArea.Text + "','" + rbJenis.SelectedValue + "',getdate()')"

           SQL.Connection = Conn

           ' With SQL

           ' .Parameters.Add(New SqlParameter("@sNoID", txtNoKadPengenalan.Text))

           ' .Parameters.Add(New SqlParameter("@sNama", txtNama.Text))

           'End With

           SQL.ExecuteNonQuery().ToString()

       Catch ex As Exception

           SimpanAduan()

           Response.Write("Proses tidak berjaya. Sila hubungi Pengurus Sistem dengan menyalin Ralat berikut : <BR>" + ex.ToString + SQL)

           Return

       Finally

           Conn.Close()

       End Try

   End Sub

What's wrong with this coding?i use Sybase as database and this is my webconfig

<connectionStrings>

<add name="AduanPelajar" connectionString="DSN=jbendmain ; Uid =jbend ; Pwd =(not show) ; trusted_connection = yes" providerName="System.Data.Odbc"/>

</connectionStrings>

ishrath wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-14-2008 1:09 PM

Hii,

even Iam getting the same error while uploading ,can anybody  help me out and here is my code.

if ((File1.PostedFile != null)&& (File1.PostedFile.ContentLength > 0))

           {

               string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);

          int a =String.Empty

               string SaveLocation = Server.MapPath("cv") + "\\" + fn;

               try

               {

                   File1.PostedFile.SaveAs(SaveLocation);

                   Response.Write("The file has been uploaded.");

               }

               catch (Exception ex)

               {

                   Response.Write("Error: " + ex.Message);

                   //Note: Exception.Message returns a detailed message that describes the current exception.

                   //For security reasons, we do not recommend that you return Exception.Message to end users in

                   //production environments. It would be better to put a generic error message.

               }

           }

           else

           {

               Response.Write("Please select a file to upload.");

           }

   }

   //This code first verifies that a file has been uploaded. If no file was selected, you receive the "Please select a file to upload" message. If a valid file is uploaded, its file name is extracted by using the System.IO namespace, and its destination is assembled in a SaveAs path. After the final destination is known, the file is saved by using the File1.PostedFile.SaveAs method. Any exception is trapped, and the exception message is displayed on the screen.  

   //6. Verify that the Submit1 subroutine appears as follows:

   private void Submit1_ServerClick(object sender, System.EventArgs e)

   {

       if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))

       {

           string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);

           string SaveLocation = Server.MapPath("cv") + "\\" + fn;

           try

           {

               File1.PostedFile.SaveAs(SaveLocation);

               Response.Write("The file has been uploaded.");

           }

           catch (Exception ex)

           {

               Response.Write("Error: " + ex.Message);

               //Note: Exception.Message returns detailed message that describes the current exception.

               //For security reasons, we do not recommend you return Exception.Message to end users in

               //production environments. It would be better just to put a generic error message.

           }

       }

       else

       {

           Response.Write("Please select a file to upload.");

       }

Plateriot wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-20-2008 12:57 AM

Ok, please explain why the following line:

cmbClinicPCPAtClinic.Items.FindByValue("HON").Selected = True

Causes a NullReferenceException...

I gave up trying to get the variable that is supposed to be in the place of "HON" ... but how retarded.... the blatent hard coding of it doesn't work either!

Object Reference Not Set To An Instance Of An Object wrote Object Reference Not Set To An Instance Of An Object
on 05-24-2008 12:17 PM

Pingback from  Object Reference Not Set To An Instance Of An Object

AtishRG wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-04-2008 3:35 AM

Hello All,,

Need your help.....

I am building a windows application using vb.net..

In that application I am accessing a our client side( there are four clients) and updating our product prices according to client product prices in a datagrid column ,, as there may be number of products I am using a background worker for each client to speed up process ,, till the prices are available i am displaying a gif image in a datagrids price cell and as soon as  prices are available I am replacing gif to prices..

My problem is .. sometime I am getting an "Object reference not set to an instance of an object", but error is not comming on any specific line.. I am not able to trace error line..

Can any one know .. in this kind of  situation ,, How can I trap the exact error line... I user try catch for ecery block of code but no use.....

Hoping quick reply .....

AtishRG

AtishRG wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 06-04-2008 3:40 AM

Here is the Stack trace... for my previous send commnet

at System.Windows.Forms.DataGridViewImageCell.PaintPrivate(Graphics g, Rectangle clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates elementState, Object formattedValue, String errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts, Boolean computeContentBounds, Boolean computeErrorIconBounds, Boolean paint)

  at System.Windows.Forms.DataGridViewImageCell.Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates elementState, Object value, Object formattedValue, String errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)

  at System.Windows.Forms.DataGridViewCell.PaintWork(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates cellState, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)

  at System.Windows.Forms.DataGridViewRow.PaintCells(Graphics graphics, Rectangle clipBounds, Rectangle rowBounds, Int32 rowIndex, DataGridViewElementStates rowState, Boolean isFirstDisplayedRow, Boolean isLastVisibleRow, DataGridViewPaintParts paintParts)

  at System.Windows.Forms.DataGridViewRow.Paint(Graphics graphics, Rectangle clipBounds, Rectangle rowBounds, Int32 rowIndex, DataGridViewElementStates rowState, Boolean isFirstDisplayedRow, Boolean isLastVisibleRow)

  at System.Windows.Forms.DataGridView.PaintRows(Graphics g, Rectangle boundingRect, Rectangle clipRect, Boolean singleHorizontalBorderAdded)

  at System.Windows.Forms.DataGridView.PaintGrid(Graphics g, Rectangle gridBounds, Rectangle clipRect, Boolean singleVerticalBorderAdded, Boolean singleHorizontalBorderAdded)

  at System.Windows.Forms.DataGridView.OnPaint(PaintEventArgs e)

  at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)

  at System.Windows.Forms.Control.WmPaint(Message& m)

  at System.Windows.Forms.Control.WndProc(Message& m)

  at System.Windows.Forms.DataGridView.WndProc(Message& m)

  at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)

  at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)

  at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

  at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)

  at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)

  at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)

  at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)

  at System.Windows.Forms.Application.Run(ApplicationContext context)

  at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()

  at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()

  at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)

  at SalesDatabase.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81

  at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)

  at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)

  at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)

  at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()

  at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)

  at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)

  at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()

  at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

  at System.Threading.ThreadHelper.ThreadStart()

Waiting for responce

AtishRG

Vids wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-14-2008 7:14 AM

Hi,

I am trying to migrate my VB6 project to VB.net.

I have an interface MyApp. I am implemeting this interfave in another project TViewAL and also have set the reference to interface MyApp as it is present in different project.

My Framework is creating object of TViewAL without adding reference for TViewAL  but adding reference to MyApp.

when I try to run

m_objCurrentApp = CreateObject("TViewAL.clsView1")

I get error Object reference not set to an instance of an object.

Any Help is appreciated !

junior web dev wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 07-17-2008 7:29 AM

thanks for this, made me realise what I was doing wrong :-) keep up the good work sir.

Glpartha wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-04-2008 8:36 PM

hi frns,

Im getting this "object reference not set to an instance of an object " Error when I try to redirect to a custom error aspx page from the Application_Start method in global.asax file. Because of this exception the control goes to Application_error method. Also similar thing happens when I try to redirect from my custom error page to the Login page upon certain conditions. Due to which it goes back to the Application_Error method and thsu goes into a loop. Kindly help resolve this problem. Its ver very urgent... kindly help... thanks in advance.

Manish Agrahari wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-05-2008 6:50 AM

hiiiii

i have a dataGridView on main page and in that dataGridView  i m showing some records. Now on click on the index of the  dataGridView dataGridView1_RowHeaderMouseClick event is fire to edit that perticular row. A new window will open with the same no of texbox as the columns with the old data to edit.

private void dataGridView1_RowHeaderMouseClick_1(object sender, DataGridViewCellMouseEventArgs e)

       {

           if (checkBox1.Checked == true)

           {

             //   MessageBox.Show(Convert.ToString(dataGridView1.CurrentRow.Index));

               Form2 obj = new Form2();

             obj.ShowDialog(this);

           }

       }

Code for f Main window:--

public partial class DataGridViewPractice : Form

   {

       public DataGridViewPractice()

       {

           InitializeComponent();

       }

       string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;user id=admin;password=;data source=c://test.mdb";

       OleDbConnection con;

       OleDbCommand cmd;

       OleDbDataAdapter da;

       DataSet ds = new DataSet();

       int i;

       private void DataGridViewPractice_Load(object sender, EventArgs e)

       {

           LoadGrid();

       }

       private void LoadGrid()

       {

           DataSet ds1 = new DataSet();

           ds1 = retrieveRecord("select * from emp");

           dataGridView1.DataSource = ds1.Tables[0];

      }

public DataSet retrieveRecord(string sql)

       {

           con = new OleDbConnection(connString);

           cmd = new OleDbCommand(sql, con);

           da = new OleDbDataAdapter(cmd);

           ds.Clear();

           ds.Dispose();

           da.Fill(ds);

           return ds;

       }

private void dataGridView1_RowHeaderMouseClick_1(object sender, DataGridViewCellMouseEventArgs e)

       {

           if (checkBox1.Checked == true)

           {

             //   MessageBox.Show(Convert.ToString(dataGridView1.CurrentRow.Index));

               Form2 obj = new Form2();

             obj.ShowDialog(this);

           }

       }

Now the code of Sub form:-----

int i=Convert.ToInt32(obj.dataGridView1.CurrentRow.Index.ToString());

           textBox1.Text = obj.dataGridView1.Rows[0].Cells[0].Value.ToString();

           textBox2.Text = obj.dataGridView1.Rows[0].Cells[1].Value.ToString();

           textBox3.Text = obj.dataGridView1.Rows[0].Cells[2].Value.ToString();

           }

}

}

but in the secind form that is sub form there is an error is coming   System.NullReferenceException - Object reference not set to an instance of an object. in the line:---

int i=Convert.ToInt32(obj.dataGridView1.CurrentRow.Index.ToString());

please help me .....................

mkagrahari@gmail.com

mkagrahari@gmail.com

mkagrahari@gmail.com

mkagrahari@gmail.com

mkagrahari@gmail.com

hemant wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-07-2008 6:17 AM

I am creating one Ajax enabled website in that. I have taken

  Ajax controls in fallowing way

AccordionAccordionPaneTabContainerTabPanelUpdatePanelDropDownList

   The problem is that

The code

((DropDownList)TabPanel3.Controls[0].FindControl("dldiv1")).

       DataValueFi    eld = ds.Tables[0].Columns["Div_Id"].ToString();

Works fine in debug mode when I run it by pressing  F11 but in release mode it gives me fallowing error .

   Object reference not set to an instance of an object.

Can any one help me

ajay sharma wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 08-12-2008 5:06 AM

I have an exception please help me to solve this.

Server Error in '/skagway' Application.

--------------------------------------------------------------------------------

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 320:        imageMyReg2.Visible = labelMyReg2.Visible = true;

Line 321:

Line 322:        string adminUser = ConfigurationManager.AppSettings["AdminUser"].ToString();

Line 323:        string password = ConfigurationManager.AppSettings["AdminPassword"].ToString();

Line 324:

Source File: e:\ajayWork\HV\Skagway\ImportSCPData.aspx.cs    Line: 322

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]

  ImportSCPData.linkButtonImportDataFromSCP_Click(Object sender, EventArgs e) in e:\ajayWork\HV\Skagway\ImportSCPData.aspx.cs:322

  System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +105

  System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +107

  System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7

  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11

  System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +174

  System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102

--------------------------------------------------------------------------------

Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42

jai wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-04-2008 1:57 AM

i have also the same problem while i compile my website

Cez wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 10-14-2008 11:49 AM

I have written a small application in .NET 1.1 (VS2003 C#) that retrieves user ID from the database. The application has one button and on click event that does everything. This application works fine. But if there is no user activity for five minutes and the user clicks the button the

"[NullReferenceException: Object reference not set to an instance of an object.]" error occurs.

What is wrong and how can I fix it???

namespace ICS.Web.Portlets.CXUserID

{

     public class Default_View : PortletViewBase

     {

           protected System.Web.UI.WebControls.Label Label0;

           protected System.Web.UI.WebControls.Button Submit;

           protected System.Web.UI.WebControls.Label lblSSN;

           protected System.Web.UI.WebControls.TextBox txtSSN;

           protected System.Web.UI.WebControls.Label lblBirthDate;

           protected System.Web.UI.WebControls.TextBox txtBirthDate;

           protected System.Web.UI.WebControls.Label lblBirthPl;

           protected System.Web.UI.WebControls.TextBox txtBirthPl;

protected System.Web.UI.WebControls.Label Label1;

           string CConnectString;

           private void Page_Load(object sender, System.EventArgs e)

           {

           }

           private void Submit_Click(object sender, System.EventArgs e)

           {

                 if (!((txtSSN.Text.Trim() == "") || (txtBirthPl.Text.Trim() == "") || (txtBirthDate.Text.Trim() == "")))

                 {

                       OdbcConnection CConnection;

                       OdbcCommand CCommand;

                       OdbcDataReader Cresult;

                       CConnectString = "dsn=????;uid=?????;pwd=???????";

                       try

                       {                      

                             CConnection = new OdbcConnection(CConnectString);

                             CConnection.Open();

                       }

                       catch(Exception)

                       {

                             return;

                       }

                       CCommand = new OdbcCommand();

                       try

                       {

                             CCommand.Connection = CConnection;

                       }

                       catch(Exception)

                       {

                             return;

                       }

                       CCommand.CommandTimeout = 20;

                       //--------- SQL Statenents ---------

                       string UserData = "select . . . “;

                       //..................................

                       CCommand.CommandText = UserData;

                       try

                       {

                             Cresult = CCommand.ExecuteReader();

                             Cresult.Read();

                             string dbUserID = Cresult["id"].ToString();

                             Cresult.Close();

                             //----------------- Desplay message box ----------------

                             string strJScript0 = "<script type='text/javascript'>alert('Your User Login is: " + dbUserID + " ')</script>";

                             this.Controls.Add(new LiteralControl(strJScript0));

                             //======================== Fin =========================

                             txtSSN.Text = "";

                             txtBirthDate.Text = "";

                             txtBirthPl.Text = "";

                       }

                       catch(Exception)

                       {

                             //----------------- Desplay message box ----------------

                             string strJScript1 = "<script type='text/javascript'>alert('No record could be found based on the data you have provided.\\nPlease make sure the information you have entered is correct \\nor contact the admission office to obtain your ID.')</script>";

                             this.Controls.Add(new LiteralControl(strJScript1));

                             //======================== Fin =========================

                             txtSSN.Text = "";

                             txtBirthDate.Text = "";

                             txtBirthPl.Text = "";

                             return;

                       }

                       CConnection.Close();

                 } // end if

                 else

                 {

                       //----------------- Desplay message box ----------------

                       string strJScript2 = "<script type='text/javascript'> alert('Please enter all required information!')</script>";

                       this.Controls.Add(new LiteralControl(strJScript2));

                       //======================== Fin =========================

                       txtSSN.Text = "";

                       txtBirthDate.Text = "";

                       txtBirthPl.Text = "";

                 }

           } //end Submit_Click

}

}

jijo wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 11-01-2008 9:34 AM

System.NullReferenceException: Object reference not set to an instance of an object. at VBookRooms.btnBookRooms_Click(Object sender, EventArgs e)

Can any one help me to get out from this .Am getting this error when am using my application remotely , but its works in local machine

hakan uzuner wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 11-01-2008 9:22 PM

thank you for information

Rajmi wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-09-2008 5:30 AM

Useful tips.

If you get this error first thing is : Make sure that you use NEW keyword to create the object that you are refered to...

ravindra wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-11-2008 1:37 AM

i couldnt figure out whre i went wrong..but getting that error

Imports System

 Module Module1

     Sub Main()

        Dim i as integer

        Dim j as integer

        Dim count as integer =1

        Dim list() as integer

        Console.writeline("\n enter the range of numbers u want to check")

        Dim k as string

        k=Console.readline()

        i= Val(k)

        Console.writeline("\n now enter the values")

         for j= 0 to i-1

          list(j)= Val(Console.readline())

         next

        j=list(0)

        Do while count<list.length-1

         count+=1

        if list(count) > j then  j= list(count)

         loop

        Console.writeline("the greatest number is {0}",j)

     End Sub

  End Module

Srinivas wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 12-13-2008 5:20 AM

Hi Raymond,

I am getting this System.NullReferenceException error in my VB.net code.

Dim strProducts As String = ""

Response.Write("Domain " & Domain.SelectedItem.Text.ToString())  <--- Error here

Domain is my dropdownlist name

Could you please help

Thanks

Srinivas

Billz64 wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-02-2009 5:54 PM

I get the error below when trying to get on my college web page?? I don't know much about computer programming, and reading the responses above, I really feel dumb about the computer. Is there any way you can help me in terms I can understand? Thank you.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]

  StudentSpace.studenthome.Page_Load(Object sender, EventArgs e) +1440

  System.Web.UI.Control.OnLoad(EventArgs e) +67

  System.Web.UI.Control.LoadRecursive() +35

  System.Web.UI.Page.ProcessRequestMain() +750

anil wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-13-2009 7:31 AM

Hi Raymond, am getting following error in my vb.net can you plz help me out..System.NullReferenceException: Object reference not set to an instance of an object.

  at ClassLibrary1.Class1.Initialize(IMapWin MapWin, Int32 ParentHandle)

  at MapWindow.Plugins_IPlugin.StartPlugin(String Key)

anil wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-13-2009 7:56 AM

hi raymond, i just went through all the blogs, i would love to know the concept of breakpoint, debugging and using your locals and watch windows, please send the references to the following anil.srishti24@gmail.com

thank you so much..

Kaizer wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 02-20-2009 8:16 AM

public void BindAssignments()

       {

               User currentUser = (User)PersistanceManager.GetPersistedObject("VirtualCampus.BusinessObjects.User");

               wsAssignmentResult[] arrAssignments = Service.InstantiateVCServiceClient().getAssignments(currentUser.UserID, Convert.ToInt32(SubjectSelector1.EnrollmentID), Convert.ToInt32(SubjectSelector1.SubjectID));

               rpAssignments.DataSource = arrAssignments;

               rpAssignments.DataBind();

        }

I get the error "Object reference not set to an instance of an object. " on the send line of this code....plz help

Chris B wrote re: System.NullReferenceException - Object reference not set to an instance of an object. 3 common causes in VB.Net.
on 05-03-2009 5:38 AM

Sup?

Great page. Thanks a lot. Was doing a tutorial for uni and couldn't figure out what it was. Read this, then realised I had the code back to front so string was a null value. So yea, thanks.

Chris

Add a Comment

(required)  
(optional)
(required)  
Remember Me?