Last post Sep 05, 2018 06:09 AM by Ackerly Xu
Sep 04, 2018 04:43 PM|JagjitSingh|LINK
I have below code on which error comes
decimal amount = decimal.TryParse(sqlReader.GetValue(1)).ToString();Thanks
Sep 04, 2018 04:45 PM|mgebhard|LINK
The openly published reference documentation explains how to use the decimal.TryParse(string s,
out decimal result) method.
Sep 04, 2018 05:16 PM|PatriceSc|LINK
Which is correct. If you look at the doc the usual pattern for TryParse is ;
- you pass the value you want to convert and the value that should receive the converted value
- it returns a boolean that tells if the conversion succeeded
You have also an extra ToString.
In this case you are perhaps going through uneedeed hops. Isn't the db side column you are trying to retrieve already a decimal ? Or if you are tyring with dealing with DBNull.Value (which comes from before having support for nullable value types), I would
add my own extension method to hide this and use just nullable types to be able to write maybe something such as :
Edit: I meant if the db side column is a decimal you could just use :
decimal amount = sqlReader.GetDecimal(1);
Sep 05, 2018 06:09 AM|Ackerly Xu|LINK
As mgebhard's link shows,you could use the method TryParse as follows.
//if the first parameter could be converted to decimal
// the method decimal.TryParse return true and the second
// parameter will be assigned value
if (decimal.TryParse(sqlReader.GetValue(1).ToString(), out amount))
// here use the variable amount
You could also use the keyword "as".
Below is my code.
using (SqlDataReader reader=com.ExecuteReader())
decimal? a = reader.GetValue(1) as decimal?;
decimal amount = a.Value;
For more information about the keyword as , please refer to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as