2016-01-30 34 views
0

我试图根据产品ID从我的Access数据库中提取产品的价格。但是,尝试执行此操作时遇到System.InvalidCastException错误。在Visual Studio中使用C#指定的强制转换无效错误

下面是我的代码段它源于错误:

protected void btnBuy_Click(object sender, EventArgs e) 
    string strProductId, strSQLSelect, strSQL; 
    decimal decUnitPrice; 

    strSQLSelect = "SELECT PromotionPrice FROM Products WHERE ProductId = @ProductID"; 
    cmd = new OleDbCommand(strSQLSelect, mDB 
    cmd.Parameters.Add("@ProductId", OleDbType.VarChar).Value = strProductId; 
    object oUnitPrice = cmd.ExecuteScalar(); 
    decUnitPrice = (decimal)oUnitPrice; //<-- Error code 

,这里是堆栈跟踪异常代码:

[InvalidCastException: Specified cast is not valid.] 
    details.btnBuy_Click(Object sender, EventArgs e) in c:\wesnpets\details.aspx.cs:60 
    System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9690930 
    System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +108 
    System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12 
    System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15 
    System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35 
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3562 

Visual Studio中表示,最后一行是其中之一造成了错误。我已经检查了我的所有代码以及我的数据库,相关字段的格式已正确设置为Decimal。但是,我仍然无法找到解决此问题的方法。

那么有什么我可能错过了?希望你能为此提出一些可能的解决方案。谢谢!

+0

该字段在数据库中可以为空吗? –

+0

你能显示异常消息吗? – enkryptor

回答

0

C#类型十进制代表一个128位数字,而数据库中的十进制数字有点不同,可以表示不同的东西。您可能可以将数据库小数点作为字符串并使用Decimal.Parse()来获取decUnitPRice。

0

我想三件事情可能发生:

  • PromotionalPrice列不是小数
  • 查询返回任何行。
  • 的PromotionalPrice列是该行空

我会做如下处理是:

if (oUnitPrice == null || Convert.IsDbNull(oUnitPrice)) 
{ 
    // no nows or PromotionalPrice column is null 
} 
else 
{ 
    // if oUnitPrice is not decimal 
    // but it can be converted to decimal it will work 
    decUnitPrice = Convert.ToDecimal(oUnitPrice); 
} 

声明:我的答案直接写在上面的代码,所以它可能不是编译。

0

我的猜测是,该表达式的返回值仅仅是一个不同的(也许数字)类型,但因为它的盒装作为object你不能使用数字转换类型转换(注意,铸造intdecimal是一个完全不同的操作比铸造objectdecimal)。例如:

object d = 1.2; var x =(十进制)d;

将失败,但(decimal)(double)d将成功。

我建议你使用Convert.ToDecimal而不是铸造,这将根据操作数的实际类型在这里做正确的事情。

相关问题