会话在当前上下文中不存在?

时间:2011-03-21 17:52:58

标签: c# asp.net mysql sql html

在尝试实现会话时遇到问题,它说它在当前上下文中不存在我错过了什么?

 protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        //database connection string
        OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite; User=x; Password=x; OPTION=3;");
        cn.Open();
        OdbcCommand cmd = new OdbcCommand("Select * from User where username=? and password=?", cn);
        DataSet ds = new DataSet();
        //Select the username and password from mysql database 

        cmd.Parameters.Add("@username", OdbcType.VarChar);
        cmd.Parameters["@username"].Value = this.Login1.UserName;

        cmd.Parameters.Add("@password", OdbcType.VarChar);
        cmd.Parameters["@password"].Value = this.Login1.Password;
        //use asp login control to check username and password

        //Session["UserID"] = "usrName";
        //set the UserID from the User Table unsure how to add this to the sql syntax above

        OdbcDataReader dr = default(OdbcDataReader);
        // Initialise a reader to read the rows from the login table.  
        // If row exists, the login is successful  

        dr = cmd.ExecuteReader();
        DataTable dt = ds.Tables[0];
        DataRow dp = dt.Rows[0];

        OdbcDataAdapter adp = new OdbcDataAdapter(cmd)
        { 
        DataTable dt = new DataTable(); 
        adp.Fill(dt); 
        if (dt.Rows.Count != 0) 
        { 
            Session("UserID") = Convert.ToString(dt.Rows[0]["UserID"]);
            e.Authenticated = true; 
            Response.Redirect("UserProfileWall.aspx"); 
        } 
    } 

2 个答案:

答案 0 :(得分:6)

应该是

Session["UserID"] = Convert.ToString(dp["UserID"]);

您需要使用方括号

答案 1 :(得分:4)

我认为您似乎认为您正在访问Session对象作为方法。你需要:

Session["UserID"] = dp["UserID"].ToString();