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;
}
(double)(int)cmdCheck.ExecuteScalar()
. – Pb-1
ExecuteScalar does not return adouble
MSDN Execute Scalar – Featherweightcast
a value perhaps you need to read up of Type CastingBoxing and UnBoxing
as well – Featherweightint
directly, either. Your comment and vote indicates you do not understand his question. – Southernlydouble
when Executing Scalar function.. come on now... I am also quite familiar with Boxing and UnBoxing as well as Implicit Casting and Explicit Casting.. – FeatherweightExecuteScalar
is just fine - you'd have the same issue withDataReader
. The double-casting is the right approach. If you're expecting the value to be a floating-point from the database, then double-check your query, since it's apparently returning an integer. – Locule"SELECT CAST(scope_identity() AS double)"
then in your code declare the followingdouble collectionCharge = (double)cmdCheck.ExecuteScalar();
– Featherweight