簡體   English   中英

在asp.net中使用會話時出現錯誤

[英]I am getting error while using sessions in asp.net

我有2個表UsersHobbies userId is primary key in Users table and it is foreign key in is primary key in table and it is foreign key in Hobbies table. I want same table and it is foreign key in table. I want same table. I want same in both tables. When user logged in he gets table. I want same userId in both tables. When user logged in he gets 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 . On next page there is hobbies page where user have to fill info and the same應該. On next page there is hobbies page where user have to fill info and the same userId`保存到“興趣愛好”表中。 我為此使用會話,但它給異常

"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();
}

我是會話和存儲過程的新手。 這是我的第一個Web應用程序。 請幫助我改善。

您不應將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
            }       
        }
    }
}

您需要首先執行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
}

當然,您需要處理異常等等,但這應該可以幫助您入門。

首先,我想通知您,您將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聲明關閉並重新打開連接“將刷新State的值”。 更多細節

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();
    }

注意:請根據您的表格字段進行更改,如果有幫助,請標記為答案!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM