Skip to content
Advertisement

How to get double value with SqlDataReader

I’m trying read data from sql database. When I run the code, it gives an error when it comes to where it should read data.

“System.InvalidCastException: Specified cast is not valid.”

I get an error. I researched my mistake but couldn’t find the solution that works for me. While the query text I wrote works in ssms, it does not work in code.

the query wokrs in ssms

edited after warnings

SOLUTİON:

I determined datatype for each column using the above query. helped me to call the required data.

Advertisement

Answer

The reason I asked for the table definition is because there are particular column types on the DB side that map to particular data types on the C# side. The screenshot posted is not enough to realistically determine the column types. The lat and long aren’t real, otherwise they’d be truncated but other than that we can’t really say

Broadly speaking:

  • If you’ve used real column type, call GetFloat(..)
  • If you’ve used float column type, call GetDouble(..)
  • If you’ve used decimal(or numeric) column type, call GetDecimal(..)

GetXxx will not convert for you because it does an unboxing cast. If your reader has a decimal in column 0 you can only call GetDecimal on it. You cannot call GetDouble and expect you really-a-decimal to be converted to a double, for the same reason as this doesn’t work:

Unboxing casts and converting casts are different things. If you want your decimal-in-an-object as a double you have to cast twice, once to unbox and once to convert:

Similarly if your thing inside reader column 0 is a decimal and you want a double you must get it as a decimal, because that’s what it really is, and then convert it:

Simple rule:

  • Pull it out according to what it really is, then convert it

As to what you have, we don’t know; your yaw could be a real and cannot be GetDouble‘d (has to be GetFloat‘d). Your alt is probably a decimal (do you really need altitude to the tenth of a picometer/pico-ft?) and cannot be GetDouble‘d (has to be GetDecimal‘d) .. but you have all the necessary info to solve this one yourself.

If all else fails and the above just went completely over your head “try changing GetDouble to GetDecimal for the line that doesn’t work. And if that doesn’t work, try changing it to GetFloat. And if that doesn’t work, supply the table definition and we’ll tell you what it should be”

Update: youve indicated they’re all varchar. Personally I would convert them to float or real – open SSMS, Design the table, change the column type to eg float and save the table. Then they can be GetDouble’d

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement