错误:指定的强制转换无效(Asp net,c#,SQL)

时间:2017-07-20 03:41:52

标签: c# asp.net sql-server visual-studio-2013

SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-IBPJNA2;Initial Catalog=GeometryFINAL;Integrated Security=True");
SqlCommand cmd;
SqlDataReader rdr;         
int intOrderNo = (int)Session["sOrderNo"]; //error is here
String strSql = "SELECT iProductID FROM orderItemsTable WHERE iOrderNo = " + intOrderNo;
cmd = new SqlCommand(strSql, con);

3 个答案:

答案 0 :(得分:1)

确保您的Session["sOrderNo"]上有值。看起来它不存在或者值不能转换为整数。

你能做的是:

SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-IBPJNA2;Initial Catalog=GeometryFINAL;Integrated Security=True");
SqlCommand cmd;
SqlDataReader rdr;
if (Session["sOrderNo"] != null)
{
   int intOrderNo = 0;
   bool result = Int32.TryParse(Session["sOrderNo"], out intOrderNo );
   if (result)
   {
      String strSql = "SELECT iProductID FROM orderItemsTable WHERE iOrderNo = " + intOrderNo;
      cmd = new SqlCommand(strSql, con);  
   }
   else
   {
       //values are not convertable to integer....
   }
}
else
{
   //your session variable doesn't exist....
}        

答案 1 :(得分:0)

会话[" sOrderNo"]在您设置时不存在或不是int类型

您需要先检查

int intOrderNo = 0;
if(Session["sOrderNo"]!=null)
{
  int.TryPasre(Session["sOrderNo"].ToString(), out intOrderNo); 
}

答案 2 :(得分:0)

在将会话值分配给变量orderno时,可能存在两种可能的情况

  1. Session["sOrderNo"]尚未初始化

  2. Session["sOrderNo"]不包含任何值。

  3. 所以为了处理这两种情况,最好的方法是

    int intOrderNo = 0;
    if(Session["sOrderNo"]!=null)
    {
      intOrderNo = Convert.ToInt32(Session["sOrderNo"]); 
    }