简体   繁体   中英

The Object cannot be cast from DBNull to other types

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 !

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

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(),
    });
}

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