0

I have a problem that to access and place the session variable inside the sql query. I got the "NullReferenceException" error. How to fix it?
mycodes

   public partial class MyConferences : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            BindGrid();
        }
    }

    private void BindGrid()
    {
        Object conference = Session["myConf"];
        string constr = ConfigurationManager.ConnectionStrings[0].ConnectionString;
        using(SqlConnection con = new SqlConnection(constr))
        {
            string query = "SELECT conferenceName, conferenceDate, conferencePlace, submissionDueDate, category FROM Conferences WHERE email = @email)";

            using(SqlCommand cmd = new SqlCommand(query))
            {

                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@email", conference.ToString());
                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
                con.Close();
                cmd.ExecuteNonQuery();
            }
        }          
    }
}

error enter image description here

user5695111
  • 111
  • 2
  • 13
  • The conference object you have retrieved from the Session dictionary is null and so you when you attempt to call ToString() on this object you get a NullReferenceException. You need to check for conference being NULL to avoid calling methods or properties on it that will result in this error. – pmcilreavy May 09 '16 at 22:03

1 Answers1

2

In a nutshell, Session["myConf"] is a NULL value, so you need to guard against that by performing a null check on that session value:

private void BindGrid()
{
    if (Session["myConf"] == null) 
    {
        return; // Or whatever you want to do.
    }

    Object conference = Session["myConf"];
    //.....
}
Jason Evans
  • 28,906
  • 14
  • 90
  • 154