我试图根据产品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。但是,我仍然无法找到解决此问题的方法。
那么有什么我可能错过了?希望你能为此提出一些可能的解决方案。谢谢!
该字段在数据库中可以为空吗? –
你能显示异常消息吗? – enkryptor