Positonic
Positonic

Reputation: 9411

Specified cast is not valid with GetFloat on SQLDataReader

I have a database column called EarlyHoursStartTime which is declared as float.

Then I have some code where I loop through the whole table with a DataReader

SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (myReader.Read())
{

    cmdInsertLocation.Parameters.AddWithValue("@EarlyHoursStartTime", myReader.GetFloat(44)); <- Error here


}

I'm getting an error on the AddwithValues line above.

"Specified cast is not valid."

myReader.GetValue(44) is showing a value of 0.0 when this happens.

I'm tried all sorts of things to get around this like putting in a default value instead if:

if (Convert.ToString(myReader.GetValue(44)) == "0.0")

but this should be unnecessary and it's not working anyway.

Why am I getting an invalid cast exception when the value is 0.0? The database field read in by the datareader is Float, so what's the problem?

Upvotes: 2

Views: 7874

Answers (2)

V4Vendetta
V4Vendetta

Reputation: 38210

As per the Mapping list

SQL Server data type CLR data type (SQL Server) CLR data type (.NET Framework)
float                SqlDouble                  Double

the SQL float maps to the double datatype, so you should try using GetDouble instead of GetFloat

Upvotes: 9

Marcus Davies
Marcus Davies

Reputation: 248

why not try

float _float = Convert.ToSingle(myReader[FloatCol].tostring());

I dont tent tend to use Oridnal locations as i find converting everything renders less problem (most of the time)

regards

Upvotes: 0

Related Questions