2012-06-18 158 views
4

我在尝试编写项目代码,但无效的特定转换错误不断出现。任何人都可以帮助我,因为我难倒了。提前致谢。“指定的转换无效”转换ExecuteScalar的结果

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 
+3

cmd.ExecuteScalar()返回什么?你检查过了吗? – BlackVegetable

+1

我没有看到任何错误的..尝试int oQty = cmd.ExecuteScalar();那么你不需要将其整理为一个整数 – Thousand

+1

尝试在第40行放置断点并检查ExecuteScalar之后的oQty。这可能是SQL异常抛出和oQty为空?你能否也显示命令文本? – Dimitri

回答

4

第41行:显然oQty不能转换为Int32。尝试

int intQuantityOnHand = Convert.ToInt32(oQty); 
+1

我很确定Convert.ToInt32将工作 – Dimitri

0

我相信错误是在第41行。把一个断点在第41行,看看oQty的价值是什么。它可能为空。

0

如果结果集为空,您应该有空检查。

if(oQty!=null){ 
    int intQuantityOnHand = (int)oQty; 
} 

也就是说,或者拖欠你的价值......

int intQuantityOnHand = (oQty==null) ? 0 : (int)oQty; 

每MSDN,ExecuteScalar返回

[T]在结果集中,他的第一行的第一列,如果结果集为空,则返回null 引用(在Visual Basic中为Nothing)。 返回最多2033个字符。

0

试试这个:

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

,然后检查if(intQuantityOnHand !=null)

0

ExecuteScalar回报The first column of the first row in the result set, or a null reference。这可能是任何事情;一个整数,null,一个字符串,varbinary。您必须检查查询的第一列的类型并将其分配给该类型的变量。

而且,你为什么这样做:

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

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