CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Raymond Lewallen

Framework Design, Agile Coach, President Oklahoma City Developers Group, Microsoft MVP C#, TDD, Continuous Integration, Patterns and Practices, Domain Driven Design, Speaker, VB.Net, C# and Sql Server

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.



Comments

breichelt said:

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.
# June 23, 2005 10:34 AM

Kanchana said:

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?
# July 1, 2005 1:56 AM

Raymond Lewallen said:

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.
# July 1, 2005 3:33 AM

mike said:

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
# July 5, 2005 10:16 PM

Raymond Lewallen said:

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.
# July 6, 2005 5:58 AM

Eric Newton said:

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...
# July 15, 2005 10:23 AM

Raymond Lewallen said:

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 :)
# July 15, 2005 10:48 AM

Raymond Lewallen said:

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.
# July 15, 2005 10:50 AM

Romi said:

You've helped me discovered my blind spot for Common Cause No. 2! Thanks =)
# July 18, 2005 11:15 PM

Raymond Lewallen said:

Glad to be of help Romi :)
# July 19, 2005 5:58 AM

Badal Kumar said:

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
# August 18, 2005 5:55 AM

Ceema said:

Thanks Raymond, it helped me to fix my problem

Ceema
# September 21, 2005 6:28 PM

Serge said:

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!
# September 30, 2005 5:40 PM

Raymond Lewallen said:

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.
# October 4, 2005 10:00 AM

Gary said:

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?
# November 17, 2005 12:44 PM

Raymond Lewallen said:

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.
# November 22, 2005 9:51 AM

Tisha Phillips said:

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!
# December 14, 2005 12:28 PM

hui said:

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")
# January 23, 2006 8:19 AM

Raymond Lewallen said:

Hui,

Dim ok as New Button
# January 23, 2006 9:38 AM

Boulent Mustafa said:

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.


# February 8, 2006 6:09 AM

Raymond Lewallen said:

Boulent,

What is the code behind clientStamp?
# February 12, 2006 10:27 PM

Nelson Hall said:

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
# February 14, 2006 1:39 PM

Raymond Lewallen said:

Nelson,

There is no way of knowing without seeing the code.
# February 14, 2006 4:42 PM

Malcolm said:

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.
# February 24, 2006 10:44 AM

Chandu said:

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
# March 24, 2006 11:17 AM

aviand said:

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.
# April 3, 2006 11:08 AM

Russ said:

Its great when you can find answers to error messages that make you go "HUH???????????????????"
# April 6, 2006 4:13 PM

Vishu said:

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
# April 20, 2006 7:04 AM

Raymond Lewallen said:

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.
# April 20, 2006 8:33 AM

Raymond Lewallen said:

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.
# April 20, 2006 8:33 AM

John said:

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
# April 20, 2006 12:26 PM

Mark said:

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!
# May 8, 2006 4:34 AM

Raymond Lewallen said:

Mark,

Which line is throwing the error?  Have you stepped through it with the debugger?
# May 8, 2006 9:49 AM

Mark said:

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!
# May 8, 2006 11:17 AM

Mohammad Porooshani said:

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
# May 10, 2006 7:36 AM

Mohammad Porooshani said:

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
# May 10, 2006 7:46 AM

Raymond Lewallen said:

Mark, read up on Using the Debugger in Visual Studio help.
# May 10, 2006 8:58 AM

Raymond Lewallen said:

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.
# May 10, 2006 11:39 AM

Mohammad Porooshani said:

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
# May 13, 2006 3:50 AM

Mohammad Porooshani said:

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
# May 13, 2006 5:08 AM

neptune7678 said:

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

# May 16, 2006 11:12 AM

Russ said:

None
# May 16, 2006 4:31 PM

Jignasa said:

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


=============================================
# May 20, 2006 6:49 AM

Samir said:

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

# May 25, 2006 4:48 AM

Niyazi Toros said:

Mohammad! dıd you use the sDs.Tables.AcceptChanges after adding the row
# June 6, 2006 8:24 AM

Mohammad Porooshani said:

yes dear Niyazi, I tried it, stil thesmae exception!
# June 7, 2006 4:41 AM

Himadrish said:

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
# June 8, 2006 9:44 AM

deejay_001 said:

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
# June 8, 2006 3:19 PM

suzy said:

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
# June 17, 2006 11:48 PM

Stan said:

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
# June 27, 2006 3:23 PM

Zia said:

<%@ 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...
# June 29, 2006 5:43 AM

Koen said:

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??
# July 3, 2006 4:40 AM

selvakumar said:

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
# July 14, 2006 10:21 AM

epoch said:

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

          &nbs