2016-05-09 31 views
0

我有一個問題,要訪問和放置SQL查詢中的會話變量。我得到了「NullReferenceException」錯誤。如何解決它?
mycodes訪問和放置到SQL查詢內部的會話變量(NullReferenceException)錯誤

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

+0

您從Session字典中檢索到的會議對象爲空,因此y當你試圖在這個對象上調用ToString()時,你會得到一個NullReferenceException異常。您需要檢查會議是否爲NULL,以避免調用會導致此錯誤的方法或屬性。 – pmcilreavy

回答

2

簡而言之,Session["myConf"]NULL值,所以你需要通過對會話值進行空校驗防範的是:

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

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