0
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 !

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
Mirzan
  • 94
  • 2
  • 13
  • 3
    Check that `dr["one_usd_to_currency"] != DBNull.Value` before converting it. This is basically the same as a regular NullReferenceException – Rob Oct 06 '16 at 05:50
  • You can fix your problem really easy using debug, check how to use it. It will help you in the future ! – mybirthname Oct 06 '16 at 05:52
  • 1
    Possible duplicate of [Object cannot be cast from DBNull to other types](http://stackoverflow.com/questions/6098646/object-cannot-be-cast-from-dbnull-to-other-types) – MakePeaceGreatAgain Oct 06 '16 at 05:59

2 Answers2

2

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);
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • Thank You Very Much ! this line of code helps me to fix this conflict very easily , Many thanks ! – Mirzan Oct 06 '16 at 06:10
-1

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(),
    });
}
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
Sukhvindra Singh
  • 200
  • 2
  • 14