Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting ExecuteScalar() result c#

why would this work

int collectionCharge = (int)cmdCheck.ExecuteScalar();

but this produces an exception

double collectionCharge = (double)cmdCheck.ExecuteScalar();

System.InvalidCastException: Specified cast is not valid.

why would it not be valid?

EDIT I am trying to simply return a single result from a query, that gets the price of some freight. So I can't turn this into an int because it must have decimals, hence trying to cast to a double. I am still learning asp.net so if there's a better way to achieve this, please do point me in the right direction :)

EDIT 2 the full code with SQL...

using (SqlCommand cmdCheck = new SqlCommand("SELECT FREIGHT_PRICE FROM FREIGHT_QUOTER_BELNL_NEW WHERE CUSTOMER_NO = @CUSTOMER_NO AND COUNTRY = @COUNTRY AND ROUND(WEIGHT_FROM,0) < @WEIGHT AND ROUND(WEIGHT_TO,0) >= @WEIGHT AND SHIPVIA = '48';", connection))
                {
                    double collectionCharge = (double)cmdCheck.ExecuteScalar();
                    FreightAmount = collectionCharge;
                }
like image 388
Stuart Avatar asked Mar 15 '13 15:03

Stuart


3 Answers

The problem here is that ExecuteScalar is returning an int which is boxed into an object. In order to convert to a double you must first unbox to an int then convert to a double

double collectionCharge = (double)(int)cmdCheck.ExecuteScalar();
like image 107
JaredPar Avatar answered Sep 28 '22 23:09

JaredPar


Use the Convert.ToXXX to avoid invalid cast exceptions.

I.E

collectionCharge=Convert.ToDouble(cmdCheck.ExecuteScalar());

As it appears that ExecuteScalar returns an Object so the code:

double collectionCharge = (double)cmdCheck.ExecuteScalar();

Could still fail

like image 20
FalloutBoy Avatar answered Sep 28 '22 22:09

FalloutBoy


With thanks to @DJKRAZE.

I updated my query to SELECT CASE(FREIGHT_PRICE AS FLOAT) which now works with the (double) cast.

double collectionCharge = (double)cmdCheck.ExecuteScalar();
like image 23
Stuart Avatar answered Sep 28 '22 22:09

Stuart