Link to home
Start Free TrialLog in
Avatar of curiouswebster
curiouswebsterFlag for United States of America

asked on

Typecasting a Decimal from SQL Query to DataTable?

Typecasting a Decimal from SQL Query to DataTable?


I set a counter, and the following 


 var shippedProductQty2 = (decimal)shippedProductRow["AllBottlesShipped"];

 throws an exception the  180th time!


System.InvalidCastException: 'Specified cast is not valid.'


Why is it right 179 times?


Is there a better way to cast this?



Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

What is the value when it fails?  ( null ? )
Avatar of curiouswebster

ASKER

This fails. I think the typecast is broken

                    decimal shippedProductQty = shippedProductRow["AllBottlesShipped"] != null ? Decimal.Parse(shippedProductRow["AllBottlesShipped"].ToString()) : -1;
SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

isn't the quantity shipped an integer and not a decimal? I don't think you can ship 1.4 of an item

ps.  Probably not so relevant but I'd have that field as required in the database ( default = 0 ) so a null wouldn't be a problem.

@David.  Bottled shipped - yes you can't have 1.4 bottles but if it was badly named had other things eg. Kgs flour then it could well be non-integral.

one normally doesn't buy 1.4 kg's of flour but would buy 1 KG x 1 and 4 x 400G units or buy 2KG and save the packaging cost and have 600 grams left over. It depends upon what units the items are packaged in.

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial