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.

This entry was posted in .Net Development, Most Popular, Patterns and Practices. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

164 Responses to System.NullReferenceException – Object reference not set to an instance of an object. 3 common causes in VB.Net.

  1. me says:

    Thanks for article but i think that if microsoft give us the name of null variable in System.NullReferenceException our problems shold be very smaller, many times the worst part is discovery what object is null, mainly in multitheaded code.

  2. Medyum says:

    thanks for sharing

  3. Syed Faisal Habib says:

    I am getting this problem: ” 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 63: End Sub
    Line 64: Private Sub AddNewRecord(ByVal name As String)
    Line 65: Dim connectionString As String = ConfigurationManager.ConnectionStrings(“ConnectionString”).ConnectionString
    Line 66: Dim myConnection As New Data.SqlClient.SqlConnection(connectionString)
    Line 67: Dim query As String = “INSERT INTO tblSupplier(Name) VALUES(@Name) ”

    I have this code behind:
    Private Sub BindData()
    Dim connectionString As String = ConfigurationManager.ConnectionStrings(“ConnectionString”).ConnectionString
    Dim myConnection As New Data.SqlClient.SqlConnection(connectionString)
    Dim ad As New Data.SqlClient.SqlDataAdapter(“SELECT * FROM tblSupplier”, myConnection)
    Dim ds As New Data.DataSet()
    ad.Fill(ds, “tblSupplier”)
    GridView1.DataSource = ds
    GridView1.DataBind()
    End Sub
    Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
    ‘ We are checking against the “ADD”
    If e.CommandName = “New” Then
    Dim name As String = (DirectCast(GridView1.FooterRow.FindControl(“txtName”), TextBox)).Text
    AddNewRecord(name)
    End If
    End Sub
    Private Sub AddNewRecord(ByVal name As String)
    Dim connectionString As String = ConfigurationManager.ConnectionStrings(“ConnectionString”).ConnectionString
    Dim myConnection As New Data.SqlClient.SqlConnection(connectionString)
    Dim query As String = “INSERT INTO tblSupplier(Name) VALUES(@Name)”
    Dim myCommand As New Data.SqlClient.SqlCommand(query, myConnection)
    myCommand.Parameters.AddWithValue(“@Name”, name)
    myConnection.Open()
    myCommand.ExecuteNonQuery()
    myConnection.Close()
    BindData()
    End Sub

  4. ghgvhvgh says:

    gvvvvvvvvvvvvvvhvghvghvg

  5. Pingback from Back to BACK and INSERT again! « System.Errors + brickbats..

  6. Abraham says:

    Hi, get the null reference exception when running the application from the server,when i run it on my local machines i dont get such error.I need your help what can i do?

    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.]
    extranet.expandasign.epages.net.agents.generatequote.productAddDlg_DialogClosed(Object sender, DialogResultEventArgs e) in c:\_development\applications\expand_a_sign\applications\extranet\expanda_extranet\agents\generatequote.aspx.cs:1145
    MetaBuilders.WebControls.DialogWindowBase.OnDialogClosed(DialogResultEventArgs e) +22
    MetaBuilders.WebControls.DialogWindowBase.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +38
    System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
    System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

    ——————————————————————————–

  7. Christabel says:

    Thanks Raymond this fixed my problem too.

  8. Chris says:

    Hi,
    I get the null reference exception when running the application from server, but I don’t get the exception when running in the local host, any idea???

  9. Joan M says:

    I run an app logged in as me on my pc and it works fine. I log onto another’s pc as me and run the SAME EXACT CODE, dlls and everything, and I get the null reference exception. The dll’s are pulled into the local machines from the same folder by an installer program. Every single dll is the same in both instances. Why would this happen when there is no difference in the code?

  10. Alejandro says:

    I’m passing to a function an object, which has one property set on null. Could it be the reason of the exception??

    Thank you, and sory if my english is not so well

  11. Chris B says:

    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

  12. Kaizer says:

    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

  13. anil says:

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

  14. anil says:

    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)

  15. Billz64 says:

    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

  16. Srinivas says:

    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

  17. ravindra says:

    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 count+=1
    if list(count) > j then j= list(count)
    loop

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

    End Sub
    End Module

  18. Rajmi says:

    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…

  19. hakan uzuner says:

    thank you for information

  20. jijo says:

    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

  21. Cez says:

    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 = ““;

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

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

    txtSSN.Text = “”;

    txtBirthDate.Text = “”;

    txtBirthPl.Text = “”;

    }

    catch(Exception)

    {

    //—————– Desplay message box —————-

    string strJScript1 = ““;

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

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

    txtSSN.Text = “”;

    txtBirthDate.Text = “”;

    txtBirthPl.Text = “”;

    return;

    }

    CConnection.Close();

    } // end if

    else

    {

    //—————– Desplay message box —————-

    string strJScript2 = ““;

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

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

    txtSSN.Text = “”;

    txtBirthDate.Text = “”;

    txtBirthPl.Text = “”;

    }

    } //end Submit_Click

    }

    }

  22. jai says:

    i have also the same problem while i compile my website

  23. ajay sharma says:

    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

  24. hemant says:

    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

  25. Manish Agrahari says:

    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

  26. Glpartha says:

    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.

  27. junior web dev says:

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

  28. Vids says:

    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 !

  29. AtishRG says:

    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

  30. AtishRG says:

    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

  31. Plateriot says:

    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!

  32. ishrath says:

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

  33. izat says:

    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 = “
    ClientScript.RegisterStartupScript(Me.GetType(), “ErrUser”, MyScript)
    txtNoKadPengenalan.Focus()
    ElseIf txtNama.Text = “” Then
    Dim MyScript As String = “
    ClientScript.RegisterStartupScript(Me.GetType(), “ErrUser”, MyScript)
    txtNama.Focus()
    Else
    SimpanAduan()
    Dim MyScript As String = “
    ClientScript.RegisterStartupScript(Me.GetType(), “ErrSave”, MyScript)

    txtNoKadPengenalan.Text = “”
    txtNama.Text = “”
    End If
    Else
    If txtNoKadPengenalan.Text = “” Then
    Dim MyScript As String = “
    ClientScript.RegisterStartupScript(Me.GetType(), “ErrUser”, MyScript)
    txtNoKadPengenalan.Focus()
    ElseIf txtNama.Text = “” Then
    Dim MyScript As String = “
    ClientScript.RegisterStartupScript(Me.GetType(), “ErrUser”, MyScript)
    txtNama.Focus()
    ‘Else
    ‘ KemaskiniAduan(lblAduan.Text)
    ‘ Dim MyScript As String = “
    ‘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 :
    ” + 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



  34. Ron Hyatt says:

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

  35. Dread says:

    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.

  36. ahmed says:

    i have received that error but when i am trying to trust assembly from ( Microsoft .NET Framework 1.1 Wizards )

  37. Hiding says:

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

  38. Andrew says:

    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?

  39. jugadee says:

    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.

  40. youyuanfun says:

    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!

  41. Leonid says:

    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.

  42. Fred C. says:

    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

  43. Jose Luis says:

    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

  44. Jose Luis says:

    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

  45. kral oyun says:

    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

  46. BalaKumar.T.L. says:

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

  47. George says:

    hi People!

  48. Megan says:

    I have problem with Application
    “Server Error in ‘/’ Application.”

  49. Sohail raza says:

    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.

  50. 李建伟 says:

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

  51. mario says:

    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

  52. Julio says:

    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

  53. Sam Eng says:

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

  54. solamudiyathu says:

    Poda en ditch punaku

  55. Byron says:

    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

  56. Peter says:

    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

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

  58. Jeff says:

    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?

  59. Arun Ashok says:

    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

  60. Judylj60 says:

    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.

  61. Saby says:

    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.

  62. Haripriya says:

    Nice Article

  63. Haripriya says:

    Nice Article

  64. praveen says:

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

  65. praveen says:

    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

  66. Fariborz says:

    Just I wanted to say thank you for nice article.

  67. Dhipak says:

    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…

  68. Tom Ng says:

    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

  69. rty says:

    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.

  70. rlewallen says:

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

  71. FuQ2 says:

    Look at this…all questions and not a single answer

    This blog is crap.

    I shit on your site

  72. Sonia says:

    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

  73. venkatesh says:

    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?

  74. Laury Burr says:

    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.

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

  75. Sahani Said: says:

    [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

  76. Pallavi says:

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

  77. Crystalite Imran says:

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

  78. Hari says:

    help me for completing datagridpaging

  79. ramprasad says:

    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.

  80. Dcoder says:

    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

  81. Neal says:

    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

  82. Dmitri says:

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

  83. Ole Frederiksen says:

    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

  84. Mike McDonald says:

    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

  85. marky says:

    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

  86. Phillip Turner says:

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

  87. vijay kumar says:

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

  88. hossman says:

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

  89. rlewallen says:

    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.

  90. Dark Otakon says:

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

  91. Melissa says:

    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?

  92. mk says:

    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

  93. elitehunter99 says:

    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

  94. Dark Otakon says:

    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.

  95. rlewallen says:

    hrubesh,

    Use the Contact link above to send me email.

  96. daffodil says:

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

  97. hrubesh says:

    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

  98. marky says:

    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

  99. Jeroen says:

    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:

    for each item in alInhoud
    sCart = sCart & item & “

    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?

  100. Ravi Dumka says:

    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

  101. Niyazi Toros says:

    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

  102. Sonalika says:

    basically for the VB.net deployment, and also windows Application

  103. Sonalika says:

    Hi!!
    Can Any1 tel me what files are required for the windows Installer n what is the sequence of it?

  104. Sonalika says:

    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

  105. S says:

    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

  106. rlewallen says:

    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.

  107. Sonalika says:

    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)

  108. epoch says:

    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?

  109. selvakumar says:

    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

  110. Koen says:

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

  111. Zia says:

    < %@ Page Language="VB" Debug="true" %>
    < %@ import Namespace="System.Data.SqlClient" %>







    < %# Container.DataItem("qty") %>


    ‘ />





    ///////////////////////////////////////////////////////////////////////
    its have the following error mes can any one solove this…
    thank
    zia…

  112. Stan says:

    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

  113. suzy says:

    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

  114. deejay_001 says:

    My problem is with this section of Code…

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

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

    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
    “);
    int count = 0;
    using (StreamReader sr = new StreamReader(proc.StandardOutput.BaseStream))
    {
    while (looking)
    {
    Response.Write(“DOING SOMETHING
    “);
    str = sr.ReadLine();
    Response.Write(“ONCE AGAIN, DOING SOMETHING ELSE
    “);
    int i = str.IndexOf(“MAC Address = “);
    Response.Write(“Just used Index of Method (or property)
    “);
    if (str == null)
    {
    looking = false;
    }
    if (i != -1)
    {
    result = str.Substring(i + “mac address = “.Length);
    looking = false;
    }
    count++;
    Response.Write(count.ToString() + “
    “);
    }
    }
    Response.Write(“Done Checking MAC
    “);
    }
    catch (Exception err)
    {
    Response.Write(err.Message);
    }
    Response.Write(“Returning NOW
    \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

  115. Himadrish says:

    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

  116. Mohammad Porooshani says:

    yes dear Niyazi, I tried it, stil thesmae exception!

  117. Niyazi Toros says:

    Mohammad! dıd you use the sDs.Tables.AcceptChanges after adding the row

  118. Samir says:

    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" %>


    Page2.aspx:

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

    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

  119. Jignasa says:

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

    =============================================

  120. Russ says:

    None

  121. neptune7678 says:

    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

  122. Mohammad Porooshani says:

    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

  123. Mohammad Porooshani says:

    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

  124. rlewallen says:

    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.

  125. rlewallen says:

    Mark, read up on Using the Debugger in Visual Studio help.

  126. Mohammad Porooshani says:

    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

  127. Mohammad Porooshani says:

    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

  128. Mark says:

    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!

  129. rlewallen says:

    Mark,

    Which line is throwing the error? Have you stepped through it with the debugger?

  130. Mark says:

    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!

  131. John says:

    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

  132. rlewallen says:

    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.

  133. rlewallen says:

    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.

  134. Vishu says:

    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

  135. Russ says:

    Its great when you can find answers to error messages that make you go “HUH???????????????????”

  136. aviand says:

    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.

  137. Chandu says:

    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

  138. Malcolm says:

    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.

  139. Nelson,

    There is no way of knowing without seeing the code.

  140. Nelson Hall says:

    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

  141. Boulent,

    What is the code behind clientStamp?

  142. Boulent Mustafa says:

    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.

  143. Hui,

    Dim ok as New Button

  144. hui says:

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

  145. Tisha Phillips says:

    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!

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

  147. Gary says:

    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?

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

  149. Serge says:

    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!

  150. Ceema says:

    Thanks Raymond, it helped me to fix my problem

    Ceema

  151. Badal Kumar says:

    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

  152. Glad to be of help Romi :)

  153. Romi says:

    You’ve helped me discovered my blind spot for Common Cause No. 2! Thanks =)

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

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

  156. Eric Newton says:

    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…

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

  158. mike says:

    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

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

  160. Kanchana says:

    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?

  161. Ben Reichelt says:

    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.

Leave a Reply