在sql查询(NullReferenceException)错误中访问并放置会话变量

时间:2016-05-09 21:35:18

标签: c# sql asp.net session

我遇到一个问题,即访问会话变量并将其置于sql查询中。我得到了" NullReferenceException"错误。如何解决?左 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();
            }
        }          
    }
}

错误 enter image description here

1 个答案:

答案 0 :(得分:2)

简而言之,Session["myConf"]NULL值,因此您需要通过对该会话值执行空值检查来防范:

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

    Object conference = Session["myConf"];
    //.....
}