我在asp.net中使用会话时遇到错误

时间:2014-04-29 03:36:02

标签: c# asp.net

我有2个表UsersHobbies。 userId is primary key in用户table and it is foreign key in爱好table. I want same userId in both tables. When user logged in he gets userId . On next page there is hobbies page where user have to fill info and the same userId`应保存到Hobbies表中。我正在使用会话,但它正在以

为例

"Error converting datatype object to int."

我的代码是:

这是用户页面上的代码

protected void loginbtn_Click(object sender, EventArgs e)
{
    SqlCommand cmd1 = new SqlCommand("select UserId from Users where username=@username and password=@password",con);
    Session["ID"] = cmd1;
}

这是业余爱好的代码:

protected void Button4_Click(object sender, EventArgs e)
{
    int id= Convert.ToInt32(Session["ID"]);
    cmd.Parameters.AddWithValue("@UserId",id);
    con.Open();
    cmd.ExecuteNonQuery();
}

我是会话和存储过程的新手。这是我的第一个网络应用。请帮我改进。

3 个答案:

答案 0 :(得分:0)

您不应将command存储在会话中,然后将其转换为integer

<强> loginbtn_Click

protected void loginbtn_Click(object sender, EventArgs e)
{
    string conString = "xxxxxxxxxxxxxxxxxxxxxxxx";
    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();
        using (var cmd = new SqlCommand(
        "select UserId from Users where username=@username and password=@password",
        con))
        {
            cmd.Parameters.AddWithValue("@username", username.Text);
            cmd.Parameters.AddWithValue("@password", password.Text);
            var id = cmd.ExecuteScalar();
            Session["ID"] = id;

        }
    }
}

<强> Button4_Click

protected void Button4_Click(object sender, EventArgs e)
{
    string conString ="xxxxxxxxxxxxxxxxxxxxxxxxxx";
    using (SqlConnection con = new SqlConnection(conString))
    {
        con.Open();
        using (var cmd = new SqlCommand("select * from Users where UserId=@UserId",con))
        {
            var id= Convert.ToInt32(Session["ID"]);
            cmd.Parameters.AddWithValue("@UserId",id);
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                //get the data
            }       
        }
    }
}

答案 1 :(得分:0)

您需要先执行SQLCommand以获取UserID的值。现在,您传递的是SQLCommand对象,显然不是整数值。要修复错误,您需要执行以下操作:

using (SqlConnection con = new SqlConnection (connectionstring))
{
 SqlCommand cmd1 = new SqlCommand("select UserId from Users where username=@username and password=@password",con);
 cmd.Parameters.AddWithValue("@username", username.Text);
 cmd.Parameters.AddWithValue("@password", password.Text);
 con.Open();
 int UID = (int)cmd1.ExecuteScalar(); //Execute command and assign value
 Session["ID"] = UID; //Now set session variable
}

当然,你需要处理异常等等,但这应该可以让你开始。

答案 2 :(得分:0)

首先,我想通知您,您要将command对象存储到Session而不是UserID。所以你收到这个错误!

Users.aspx页面上:

在会话中存储UserID:

 using (SqlConnection con = new SqlConnection (yourConnectionString))
    {
     SqlCommand mycmd = new SqlCommand("select UserId from Users where  username=@username and password=@password",con);
    //add parameters to pass the username & password here
      mycmd.Parameters.AddWithValue("@username", username.Text);
      mycmd.Parameters.AddWithValue("@password", password.Text);
     if (con.State != ConnectionState.Open)
      {
           con.Close();
           con.Open();
      }

     int userID = (int)mycmd.ExecuteScalar();
     Session["UserID"] = userID; //Store USerID in session
     con.Close();
    }

我不仅仅使用以下原因:

if (con.State == ConnectionState.Closed)
{
    con.Open();
}

是因为ConnectionState也可以是:

Broken, Connnecting, Executing, Fetching

此外,Microsoft声明关闭,然后重新打开连接&#34;将刷新State的值。&#34; More Details

Hobbies.aspx页面上:

使用会话用户ID:

if(Session["UserID"]!=null)
{
int userID=Convert.ToInt32(Session["UserID"])
//do other stuff
}

插入爱好表:

private void btnInsertHobbies_Click(object sender, EventArgs e)
    {
        int userID=0;
        if(Session["UserID"]!=null)
        {
          userID=Convert.ToInt32(Session["UserID"]);
        }

        //add Here fields of hobbies table
        string hobby1= textBox2.Text;
        string hobby2= textBox3.Text;
        if (conn2.State != ConnectionState.Open)
        {
           conn2.Close();
           conn2.Open();
        }

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn2;
        cmd.CommandText = "INSERT INTO Hobbies(userID, hobby1, hobby2)   VALUES(@userID,@hobby1,@hobby2)";

        cmd.Parameters.AddWithValue("@userID", userID);
        cmd.Parameters.AddWithValue("@hobby1", hobby1);
        cmd.Parameters.AddWithValue("@hobby2", hobby2);

        cmd.ExecuteNonQuery(); 

        conn2.Close();
    }

注意:请根据您的表格字段进行更改,如果有帮助,请将其标记为答案!