Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specified cast is not valid – SQL float to C# double

In my c# code, I have a double that I am trying to set to the value that is in my SQL Management 2008 R2 database that is of type float (which corresponds to a double in c#, right?). When I use this syntax

double x = (double)reader["column1"]; //reader is SqlDataReader object

I get the error "specified cast is not valid."

What gives?

like image 708
Skitterm Avatar asked Aug 01 '12 19:08

Skitterm


1 Answers

I would suggest using the helper classes available through the SqlDataReader object...

double dbl = reader.GetDouble(reader.GetOrdinal("DoubleColumn"));

If there is a chance the column could be null, you should account for that...

double dbl = (reader["DoubleColumn"] != DBNull.Value ? dr.GetDouble(dr.GetOrdinal("DoubleColumn")) : 0.0);
like image 154
CoderMarkus Avatar answered Oct 20 '22 03:10

CoderMarkus