Conversion failed when converting the nvarchar value to data type int

后端 未结 2 1809
故里飘歌
故里飘歌 2021-01-26 11:05

I am getting the error of conversion failed in my codebehind. My code is below:

using (SqlCommand cmd = new SqlCommand((tempUsertype == \"0\" ? \"Select * from t         


        
相关标签:
2条回答
  • 2021-01-26 11:26

    I guess that NgoId is an int but you're assigning a string. So this might fix it:

    var p = new SqlParameter("@NgoId", SqlDbType.int).Value = int.Parse(Convert.ToString(Session["User"]));
    cmd.Parameters.Add(p);
    

    Edit: since you have commented that the session stores the username but the NgoId is an int-column you have three options:

    1. change the session to store the user-id int instead of the name
    2. change the column to store the username
    3. select the user-id from the table where the username is stored.

    I would either prefer the first or the last option.

    This works if you also prefer the last approach:

    string sql = "Select * from tbl_students";
    if(tempUsertype != "0")
    {
        sql = @"Select s.* 
                from tbl_students s 
                where s.NgoId in (Select u.NgoId 
                                  from tbl_User u 
                                  where u.username = @Username)";
    }
    using (var cmd = new SqlCommand(sql, conn))
    {
        var p = new SqlParameter("@Username", SqlDbType.varchar);
        p.Value = Convert.ToString(Session["User"]);
        cmd.Parameters.Add(p);
        // ...
    }
    
    0 讨论(0)
  • 2021-01-26 11:35

    Try this:

    cmd.Parameters.Add("@NgoId", SqlDbType.Int).Value = Convert.ToString(Session["User"]);
    

    This will coerce the NgoId parameter to the SQL Server int data type.

    0 讨论(0)
提交回复
热议问题