Object cannot be cast from DBNull to other types using DBNull.Value ? Convert

StackOverflow https://stackoverflow.com/questions/22384613

  •  14-06-2023
  •  | 
  •  

Frage

I am trying to read the values out of a database that I am aware is null in the criteria I am looking for right now. So I had this method of checking for that: ld.Percentage = reader["DataWin3Data"] != DBNull.Value ? Convert.ToDouble(reader["DataWin3Data"]) : double.MinValue; I have used it before where a field can be null and it hasn't had a problem. I am not totally sure what to do in this situation as to how to fix it. I have included my relevant code below. How can change what I am doing currently to not have have this error when there is a null value?

ld.Percentage = reader["DataWin3Data"] != DBNull.Value ? Convert.ToDouble(reader["DataWin3Data"]) : double.MinValue;
ld.TotalCases = reader["DataWin8Data"] != DBNull.Value ? Convert.ToInt32(reader["DataWin8Data"]) : int.MinValue;
ld.TotalPercentage = reader["DataWin7Data"] != DBNull.Value ? Convert.ToDouble(reader["DataWin7Data"]) : double.MinValue;
War es hilfreich?

Lösung

What about this?

ld.Percentage = reader["DataWin3Data"] == DBNull.Value 
                ? double.MinValue : (double)reader["DataWin3Data"];

I've used code like this many times without issue. Are you sure that you're always reading the same field that you're also checking for null?

Also, don't use Convert when you're not actually converting. This should be a cast (like in my example).

If that doesn't work, it might be that you're doing something weird with the data. Perhaps some serialization on the way? Try this:

ld.Percentage = reader["DataWin3Data"] is DBNull 
                ? double.MinValue : (double)reader["DataWin3Data"];
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top