我遇到一个问题,即访问会话变量并将其置于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();
}
}
}
}
答案 0 :(得分:2)
简而言之,Session["myConf"]
是NULL
值,因此您需要通过对该会话值执行空值检查来防范:
private void BindGrid()
{
if (Session["myConf"] == null)
{
return; // Or whatever you want to do.
}
Object conference = Session["myConf"];
//.....
}