C# “指定的转换无效”转换 ExecuteScalar 的结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11089939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Specified cast is not valid" casting the results of ExecuteScalar
提问by user1464667
I'm trying to code for a project, but the non-valid specific cast error keeps coming out. Can anyone help me as I am stumped. Thanks in advance.
我正在尝试为一个项目编码,但不断出现无效的特定转换错误。任何人都可以帮助我,因为我很难过。提前致谢。
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
回答by Eren Ers?nmez
Line 41: apparently oQtycannot be cast to Int32. Try
第 41 行:显然oQty不能强制转换为Int32. 尝试
int intQuantityOnHand = Convert.ToInt32(oQty);
回答by Kevin Aenmey
I believe the error is on line 41. Put a breakpoint on line 41 and see what the value of oQty is. It could be null.
我相信错误在第 41 行。在第 41 行放置一个断点,看看 oQty 的值是多少。它可能为空。
回答by David Hoerster
You should have a null check in case your result set is empty.
如果您的结果集为空,您应该进行空检查。
if(oQty!=null){
int intQuantityOnHand = (int)oQty;
}
That, or default your value...
那,或默认您的价值...
int intQuantityOnHand = (oQty==null) ? 0 : (int)oQty;
Per MSDN, ExecuteScalarreturns
根据 MSDN,ExecuteScalar返回
[t]he first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.
[t]结果集中第一行的第一列,如果结果集为空,则为空引用(在 Visual Basic 中为 Nothing)。最多返回 2033 个字符。
回答by Harry89pl
try this:
尝试这个:
object oQty = cmd.ExecuteScalar();
int? intQuantityOnHand = (oQty as int);
and then check if(intQuantityOnHand !=null)
然后检查 if(intQuantityOnHand !=null)
回答by Dour High Arch
ExecuteScalarreturns The first column of the first row in the result set, or a null reference. This could be anything; an integer, null, a string, varbinary. You have to examine the type of the first column of your query and assign to a variable of that type.
ExecuteScalar返回结果集中第一行的第一列,或者一个空引用。这可以是任何东西;整数、空值、字符串、varbinary。您必须检查查询第一列的类型并分配给该类型的变量。
Also, why are you doing this:
另外,你为什么要这样做:
int intBuyQuantity = int.Parse(ddlQty.Items[ddlQty.SelectedIndex].ToString());
You're converting something to a string, then the string to an integer. Why? Is it a string? Then that can throw an exception. Is it an integer? Then read it as an integer. Are you using System.Data.SqlClient? That contains methods like GetInt32which return data of the proper type; you don't need to cast, parse, or whatever.
您正在将某些内容转换为字符串,然后将字符串转换为整数。为什么?是字符串吗?然后可以抛出异常。是整数吗?然后将其作为整数读取。你在用System.Data.SqlClient吗?包含GetInt32返回正确类型数据的方法;您不需要强制转换、解析或其他任何内容。

