0

I have tried many things but its just showing error "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:

                 else if (Session["StudId"] != null)
             {
                 Label1.Text = Session["StudId"].ToString();
             }

I have written this code in my login page dragging all the required databases strings i.e. typeid,students,faculty,admin and accemployee in the page.

public partial class Login : System.Web.UI.Page
 {private string strcon = WebConfigurationManager.ConnectionStrings["StudentConnectionString1"].ConnectionString;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Request.Cookies["UName"] != null)
            TextBox1.Text = Request.Cookies["UName"].Value;
        if (Request.Cookies["PWD"] != null)
            TextBox2.Attributes["value"] = Request.Cookies["PWD"].Value;
        if (Request.Cookies["UName"] != null && Request.Cookies["PWD"] != null)
            CheckBox1.Checked = true;
    }
}
protected void Button1_Click1(object sender, EventArgs e)
{

    if (DropDownList1.SelectedItem.Value == "1")
    {
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("Select StudFirstName from Student where StudId=@sid and Password=@pw", con);
        cmd.Parameters.AddWithValue("@sid", TextBox1.Text);
        cmd.Parameters.AddWithValue("@pw", TextBox2.Text);
        con.Open();
        string name = Convert.ToString(cmd.ExecuteScalar());
        con.Close();

        if (String.IsNullOrEmpty(name))
            Label1.Text = "Sorry! Invalid User ID or Password!";
        else
        {
            if (CheckBox1.Checked)
            {
                Response.Cookies["UName"].Value = TextBox1.Text;
                Response.Cookies["PWD"].Value = TextBox2.Text;
                Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
                Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
            }

            Session.Add("StudId", TextBox1.Text);
            Session.Add("StudFirstName", name);
            Session.Add("Password", TextBox2.Text);
            FormsAuthentication.RedirectFromLoginPage(name, false);
        }
    }





      else if (DropDownList1.SelectedItem.Value == "2")
    {
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("Select FacultyFirstName from Faculty where FacultyId=@fid and Password=@pw", con);
        cmd.Parameters.AddWithValue("@fid", TextBox1.Text);
        cmd.Parameters.AddWithValue("@pw", TextBox2.Text);
        con.Open();
        string name = Convert.ToString(cmd.ExecuteScalar());
        con.Close();
        if (String.IsNullOrEmpty(name))
            Label1.Text = "Sorry! Invalid User ID or Password!";
        else
        {
            if (CheckBox1.Checked)
            {
                Response.Cookies["UName"].Value = TextBox1.Text;
                Response.Cookies["PWD"].Value = TextBox2.Text;
                Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
                Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
            }
            Session["FacultyId"] = TextBox1.Text;
            Session.Add("FacultyFisrtName", name);
            Session["Password"] = TextBox2.Text;
            FormsAuthentication.RedirectFromLoginPage(name, false);
        }
    }
    else if (DropDownList1.SelectedItem.Value == "3")
    {
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("Select AccEmployeeName from AccEmployee where AccEmployeeId=@aid and Password=@pw", con);
        cmd.Parameters.AddWithValue("@aid", TextBox1.Text);
        cmd.Parameters.AddWithValue("@pw", TextBox2.Text);
        con.Open();
        string name = Convert.ToString(cmd.ExecuteScalar());
        con.Close();
        if (String.IsNullOrEmpty(name))
            Label1.Text = "Sorry! Invalid User ID or Password!";
        else
        {
            if (CheckBox1.Checked)
            {
                Response.Cookies["UName"].Value = TextBox1.Text;
                Response.Cookies["PWD"].Value = TextBox2.Text;
                Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
                Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
            }
            Session["AccEmployeeFacultyId"] = TextBox1.Text;
            Session.Add("AccEmployeeName", name);
            Session["Password"] = TextBox2.Text;
            FormsAuthentication.RedirectFromLoginPage(name, false);
        }
    }
    else if (DropDownList1.SelectedItem.Value == "4")
    {
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("Select  from Admin where AdminId=@pid and Password=@pw", con);
        cmd.Parameters.AddWithValue("@pid", TextBox1.Text);
        cmd.Parameters.AddWithValue("@pw", TextBox2.Text);
        con.Open();
        string name = Convert.ToString(cmd.ExecuteScalar());
        con.Close();
        if (String.IsNullOrEmpty(name))
            Label1.Text = "Sorry! Invalid User ID or Password!";
        else
        {
            if (CheckBox1.Checked)
            {
                Response.Cookies["UName"].Value = TextBox1.Text;
                Response.Cookies["PWD"].Value = TextBox2.Text;
                Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
                Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
            }
            string adminName = "Pujan";
            Session["AdminId"]=TextBox1.Text;
            Session["AdminName"] = adminName;
            Session["Password"]=TextBox2.Text;
            FormsAuthentication.RedirectFromLoginPage(name, false);
        }
    }

}


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label2.Text = DropDownList1.SelectedItem.Text;

}

` }

..................................................................................... Now the error occurs in the masterpage.master.cs which is shown below....

  public partial class MasterPage : System.Web.UI.MasterPage
{
   protected void Page_Load(object sender, EventArgs e)

{

            if (Session["StudId"] == null)
            Response.Redirect("Login.aspx");

            else if (Session["StudId"] != null)
            {
                Label1.Text = Session["StudId"].ToString();
            }


            else if (Session["FacultyFirstName"] == null)
            {
                Response.Redirect("Login.aspx");
            }

            else if (Session["FacultyFirstName"] != null)
            {
                Label1.Text = Session["FacultyFirstName"].ToString();
            }

            else if (Session["AccEmployeeName"] == null)
            {
                Response.Redirect("Login.aspx");
            }

            else if (Session["AccEmployeeName"] != null)
            {
                Label1.Text = Session["AccEmployeeName"].ToString();
            }

            else if (Session["AdminName"] == null)
            {
                Response.Redirect("Login.aspx");
            }

            else if (Session["AdminName"] != null)
            {
                Label1.Text = Session["AdminName"].ToString();
            }


}



protected void LinkButton1_Click1(object sender, EventArgs e)
{
    FormsAuthentication.SignOut();
    Response.Redirect("Login.aspx");
}

}

Please suggest me how to get rid of the error in session or wateva it is......Thank you in advance :)

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
  • See [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). Most likely `Label1` is `null`. – CodeCaster Mar 21 '14 at 15:56

1 Answers1

0

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

This error means that the value that is being provided is a null and the Server cannot use it for a process, that requires a parameter to work on.

Sometimes this happens when you're trying to use a variable in a method, and the variable gets a null value. Null value means that there is no value or no data for this thing.

In your code I guess that this error would generate when the site is first loading. At that time, there is no Session for the Server to load or work on. Thus the values are all null throwing this Null exception.

You can try to cover up the code inside an if else block to check whether there is a cookie present for the Session, or try out a try catch block to minimize this exception and do the work depending on the condition.

An example would be:

try {
   /* your code here */
} catch (System.NullReferenceException) {
   /* create a session or fill up the variable */
}

This block would run the code of yours, and if the exception provided inside the Catch method gets thrown it would execute the code inside the catch block.

Second thing was to use if else:

if(variable != null) {
   /* your code here */
} else {
   /* set the value */
}

You just check for the value of that particular variable, and check it. If its a null valued variable, then you can skip the execution of the code block and fill the variable with a value and then come back to the current space and re-execute it.

For exception details: http://msdn.microsoft.com/en-us/library/system.nullreferenceexception(v=vs.110).aspx

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103