Showing posts with label cost. Show all posts
Showing posts with label cost. Show all posts

Sunday, February 12, 2012

casting float output param throws an exception.

I keep getting an exception when trying to cast an output param as a float type. the SPROC is marked as float OUTPUT and the Cost column in the database is a float type as well. And there are no nulls in the cloumn either. here is how my code looks:


SqlParameter prmCost= new SqlParameter("@.Cost", SqlDbType.Float,8);
prmCost.Direction=ParameterDirection.Output;
cmd.Parameters.Add(prmCost);

//...blah blah blah

//invalid cast gets throw on here (it happens with all my float types)
productDetails.Cost=(float)prmCost.Value;

Any suggestions as to what I am doing wrong?You have to use the <datatype>.Parse() methods to covert to numbers, e.g.


float test = float.Parse(prmCost.Value.ToString());
|||If you do a watch on prmCost before the error do you see a reasonable value in there?

If so, maybe try the cast with a double on the .Net side and see if you can get it in. Try the code below to help debug. If it still crashes maybe the exception message will be more helpful than your current one.


string message = "";
double doubleValue = 0.0;
try{
string seeWhatsThere = prmCost.Value.ToString();
// put a watch on seeWhatsThere to see what it looks like
doubleValue = System.Double.Parse( seeWhatsThere );
}
catch( FormatException ex){
message = ex.Message;
}
catch( Exception ex ){
message = ex.Message;
}

|||Yes, there is a reasonable value for the parameter (I check the param for a null value before attempting to cast it). I did it as follows, but I'm not sure if I will loose any precision this way. From what I understand Single is the same thing as float, correct me if I'm wrong.


product.Cost=Convert.ToSingle(prmCost.Value);

Thanks for the help.