Reputation: 65
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"));
Upvotes: 0
Views: 4772
Reputation: 1447
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"));
Upvotes: 0
Reputation: 101778
Have you tried:
var value = DataBinder.Eval(e.Row.DataItem, "December2013DailyOrderCount");
Convert.ToDecimal(value == DbNull.Value ? 0 : value);
Upvotes: 0
Reputation: 109210
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.
Upvotes: 3
Reputation: 157146
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
Upvotes: 0