简体   繁体   中英

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

I have a error which is a result of a null value. I want all null values to display as a 0 . How do I do this?

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.

This is the line flagged up.

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

The easiest way would be to modify your SQL to use ISNULL to convert null into a default value.

Otherwise you need conditional logic in your web application code. How easy this is depends on the context. In markup (eg. item template) it can be harder, in code behind just get the underling value into a temporary, and if null return 0.

Just do an additional check on the value being DBNull.Value :

var input = DataBinder.Eval(e.Row.DataItem, "December2013DailyOrderCount");
var x = (input == DBNull.Value) ? 0 : (decimal)input;

Another option is to fix this in your query, like this:

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

Have you tried:

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

I think its good to create a code behind function and call the function while binding the data:

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM