ASP.NET - Object reference not set to the instance of an object

Asked By amala mandarapu on 13-Jul-12 07:18 AM
hi all,
i am facing "object reference not set to the instance of an object" error in the following code.


protected void Page_Load(object sender, EventArgs e)


{

roleID =

Convert.ToInt32(Session["roleId"]);



if (Request.QueryString["EmployeeID"] != null)


{

empId = Request.QueryString[

"EmployeeID"];


}


else


{

empId = (

string)Session["LoginId"];


}


if (!IsPostBack)


{


try


{

RetrieveEmpInfo();

Session[

"ViewEmpid"] = null;



if (roleID == 1 || roleID == 2 || roleID == 3)


{

pnlApprovals.Visible =

true;


pnlLeave.Visible =

true;


}


else


{

pnlApprovals.Visible =

false;


pnlLeave.Visible =

false;


}

GetEmployeeLeaveApprovalsandSubmissions();

GetPendingApplyLeavses();

}


catch (Exception ex)


{


if (log.IsErrorEnabled)


{

log.Error(ex.Message);

}

}

}

}



please check and let me the issues when it happen.
Sathish S replied to amala mandarapu on 13-Jul-12 07:19 AM
That's a common error when you try access a property or method of a class without instantiating it.

Post your code or stack trace to get a detailed response.
amala mandarapu replied to Sathish S on 13-Jul-12 07:22 AM
i posted my code.in my stack trace in page load i am facing that error.
in log file it is showing that error but when i am debugging my code i am not facing any error.

please check the code and help me.
Sathish S replied to amala mandarapu on 13-Jul-12 07:51 AM

empId = (string)Session["LoginId"]; This line could cause a null ref exception. It is difficult to find out the error with the partial code. However you can print the Session and View state values inside your Exception block to trace whether all the objects have expected values.

amala mandarapu replied to Sathish S on 13-Jul-12 07:54 AM
now i checked in the same way what you said i am facing some other exceptions.
Jitendra Faye replied to amala mandarapu on 13-Jul-12 08:39 AM
In your code you are accessing Session value , so before access check for null.

like this-

if(Session["roleid"] != null)
 {
    //your code
 }


Rohan Dave replied to amala mandarapu on 14-Jul-12 06:22 AM
It's a common error and cause of this error is , when you are trying to access any objects which is not instantiated then you will get this error..

Here in you code, i am seeing some of the suspected places which cause this error..

1) roleID = Convert.ToInt32(Session["roleId"]);   // make sure you have defined "Session["roleId"] " before accessing in your code
2) Request.QueryString["EmployeeID"] // make sure you have "EmployeeID" in your querystring
3) empId = (string)Session["LoginId"];  // make sure you have defined "Session["LoginId"]" before accessing in your code

This three are the suspected places. Try to debug your code and let's see the value of this.. Also if error is not coming from this places try to debug your methods.