C# &引用;指定的强制转换无效";铸造ExecuteScalar的结果

C# &引用;指定的强制转换无效";铸造ExecuteScalar的结果,c#,asp.net,C#,Asp.net,我试图为一个项目编写代码,但无效的特定强制转换错误不断出现。有谁能帮助我,因为我被难倒了。提前谢谢 Server Error in '/c#project' Application. Specified cast is not valid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for

我试图为一个项目编写代码,但无效的特定强制转换错误不断出现。有谁能帮助我,因为我被难倒了。提前谢谢

Server Error in '/c#project' Application.

Specified cast is not valid.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error: 


Line 39:         cmd.Parameters.Add("@ProductId", OleDbType.Char).Value = strProductId;
Line 40:         object oQty = cmd.ExecuteScalar();
Line 41:         int intQuantityOnHand = (int)oQty;
Line 42:         mDB.Close();
Line 43:         int intBuyQuantity = int.Parse(ddlQty.Items[ddlQty.SelectedIndex].ToString());

Source File: c:\Users\jacob\Desktop\c#project\ProductDetails.aspx.cs    Line: 41 

Stack Trace: 


[InvalidCastException: Specified cast is not valid.]
   ProductDetails.btnBuy_Click(Object sender, EventArgs e) in c:\Users\jacob\Desktop\c#project\ProductDetails.aspx.cs:41
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272

第41行:显然,
oQty
不能强制转换为
Int32
。试一试

int intQuantityOnHand = Convert.ToInt32(oQty);

我相信错误在第41行。在第41行放置一个断点,看看oQty的值是多少。它可能为空。

如果结果集为空,则应该进行空检查

if(oQty!=null){
  int intQuantityOnHand = (int)oQty;
}
或者默认值

  int intQuantityOnHand = (oQty==null) ? 0 : (int)oQty;
根据MSDN,返回

[t] 结果集中第一行的第一列,或null 如果结果集为空,则引用(Visual Basic中无任何内容)。 返回最多2033个字符

试试这个:

object oQty = cmd.ExecuteScalar();
int? intQuantityOnHand = (oQty as int);

然后检查是否(intQuantityOnHand!=null)
ExecuteScalar
返回。这可以是任何东西;整数、null、字符串、varbinary。您必须检查查询的第一列的类型,并将其分配给该类型的变量

还有,你为什么要这样做:

int intBuyQuantity = int.Parse(ddlQty.Items[ddlQty.SelectedIndex].ToString());

你要把一些东西转换成一个字符串,然后把字符串转换成一个整数。为什么?它是一根绳子吗?这样就可以抛出一个异常。它是整数吗?然后将其作为整数读取。您正在使用
System.Data.SqlClient
?包含返回正确类型的数据的方法,如
GetInt32
;您不需要强制转换、解析或其他任何操作。

cmd.ExecuteScalar()返回什么?你检查过了吗?我看没有什么问题。。试试int-oQty=cmd.ExecuteScalar();然后,您不需要将其装箱到整数,在第40行放置断点,并检查ExecuteScalar之后的oQty是什么。可能是sql异常被抛出,而oQty为空?你也可以显示命令文本吗?我已经编辑了你的标题。请参阅“”,其中的共识是“不,他们不应该”。