[英]Object cannot be cast from DBNull to other types error shown?
我的代码是这样
private MyCatch _catch = new MyCatch("Description");
decimal getTotalValue(GridView view, int listSourceRowIndex)
{
decimal unitPrice = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Each")); //Object cannot be cast from DBNull to other types
decimal quantity = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Quantity"));
decimal discount = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "TaxPercentage"));
return unitPrice * quantity * (1 - discount);
}
private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
{
GridView view = sender as GridView;
if (e.Column.FieldName == "Totalototal" && e.IsGetData) e.Value =
getTotalValue(view, e.ListSourceRowIndex);
}
在这里,我假设在Null的情况下将unitPrice设置为0。
decimal unitPrice = view.GetListSourceRowCellValue(listSourceRowIndex, "Each") == DBNull.Value
? 0
: Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Each"));
如果可以有null值,请尝试使用可为null的类型。
decimal? unitPrice = ...
可为空的类型是一种将null作为值的值类型。 然后可以检查值
if (unitPrice.HasValue) // is there a value or null?
unitPrice.Value // do something with the value
有关MSDN上的 nullables的更多信息。
但是我假设不应接收null,这将使计算变得不可能。 因此,我建议将获取值封装在try/catch
块中,如果某些调用引发异常,则从方法中返回。
您可以使用TryParse
方法来确定是否可以从给定值转换为十进制。如果不可能,则分配DBNull.Value
语法: decimal.TryParse(value,out parameter)
如果该值可以强制转换为decimal
则上述函数返回true
如果无法投放,则返回false
当需要在表列中插入Null
,应从代码中插入DBNull.Value
。 因此您可以在无法进行强制转换时发送DBNull.Value
。
注意:这里我使用三元?:
运算符将整个事情写在单行中
解:
decimal result;
decimal unitPrice =(decimal.TryParse(view.GetListSourceRowCellValue(listSourceRowIndex, "Each"),out result))?result:DBNull.Value;
问题是因为,从中获取的数据值可能包含DBNull值,这意味着该值不存在。
因此,更改不存在的值的类型没有意义。
允许null的解决方案是,将变量声明为可为null的类型,这意味着它们能够接受null值。
语法是:
datatype? variablename
霍普这有帮助。
我正在使用GridView和RowDataBound事件对ASP.net VB进行编程,在某些行中,数据库中的值为空:
If e.Row.RowType = DataControlRowType.DataRow Then
If (DataBinder.Eval(e.Row.DataItem, "MyField") IsNot DBNull.Value) Then
myTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "MyField"))
End If
End If
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.