Reputation: 94
List<exchange_rates> exch_rate_list = new List<exchange_rates>();
foreach (DataRow dr in ExchangeRates.Rows)
{
exch_rate_list.Add(new exchange_rates {
one_usd_to_currency = Convert.ToDouble(dr["one_usd_to_currency"]),
currency = dr["currency"].ToString(),
});
}
Well I am getting a error saying Object cannot be cast from DBNull to other types at this point one_usd_to_currency = Convert.ToDouble(dr["one_usd_to_currency"])
, can someone please guide me on this bug, where i have tried many ways of handling by changing Data Types , i do really appreciate if you could guide me on this bug in order to solve this conflict , many thanks !
Upvotes: 0
Views: 117
Reputation: 198
You can try like....
foreach (DataRow dr in ExchangeRates.Rows) {
if (dr["one_usd_to_currency"] == null)
dr["one_usd_to_currency"] = 0;
exch_rate_list.Add(new exchange_rates {
one_usd_to_currency = Convert.ToDouble(dr["one_usd_to_currency"]),
currency = dr["currency"].ToString(),
});
}
Upvotes: -1
Reputation: 37000
When you get DBNull
as result you have to use this code as DBNull
is an own type that cannot be cast to anything different System.Object
:
var dbValue = dr["one_usd_to_currency"];
if(dbValue != DBNull.Value) one_usd_to_currency = Convert.ToDouble(dbValue);
Upvotes: 2