user5695111 user5695111 - 7 months ago 14
SQL Question

Acces and place to session variable inside the sql query (NullReferenceException) error

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

Answer

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"];
    //.....
}