我如何在 .net c# 中将 DBNull 转换为 0?

How do i convert DBNull to 0 in .net c#?

我有一个错误,这是 null 值的结果。我希望所有 null 值都显示为 0。我该怎么做?

Object cannot be cast from DBNull to other types.

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: Object cannot be cast from DBNull to other types.

这是标记的行。

Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "December2013DailyOrderCount"));

只需对 DBNull.Value:

的值进行额外检查
var input = DataBinder.Eval(e.Row.DataItem, "December2013DailyOrderCount");
var x = (input == DBNull.Value) ? 0 : (decimal)input;

另一种选择是在您的查询中修复此问题,如下所示:

select coalesce
       ( December2013DailyOrderCount
       , 0
       )
       December2013DailyOrderCount -- column alias!!!
from   xxx

最简单的方法是修改 SQL 以使用 ISNULL 将 null 转换为默认值。

否则,您的 Web 应用程序代码中需要条件逻辑。这有多容易取决于上下文。在标记(例如项目模板)中它可能更难,在代码后面只是将底层值放入临时值,如果为空 return 0.

你试过了吗:

var value = DataBinder.Eval(e.Row.DataItem, "December2013DailyOrderCount");
Convert.ToDecimal(value == DbNull.Value ? 0 : value);

我认为创建一个代码隐藏函数并在绑定数据时调用该函数很好:

protected decimal ConvertNullDecinalToZero(object val){
  decimal number;
  if (Decimal.TryParse(value, out number))
     return number
 else
     return 0; 
}


var input = DataBinder.Eval(e.Row.DataItem, Convert("December2013DailyOrderCount"));