My SQL data of column Price is of type float.
When I use DataReader to read in a row and try to access the column value as
reader["Price"]
I got a compiler error: “The best overloaded method match for decimal.Parse(string) has some invalid arguments.”
I want assign this value to a decimal variable, how do I do so?
I got the compiler error above when I tried:
decimal price;
price = decimal.Parse(reader["Price"]);
The return type for
reader["Price"]isobject. To do what you’re trying to do use this:However, if there’s the slightest change you can end up with a string that cannot be converted to a Decimal consider using the Decimal.TryParse Method which will allow you to determine if the conversion was successful.
EDIT
The SqlDataReader has a number of different GetXXX methods that allow you to retrieve typed data from a column in a DataReader without first having to cast to/from an intermediate type. I originally advised you to use
SqlDataReader.GetDecimalbecause I saw the type you wanted to retrieve is a decimal. I see now that the SQL data type of the this data is actually float so I was going to advise that you useSqlDataReader.GetFloat. I tested this though and got an invalid cast exception. The reason for this is that the SQL float is not compatible with the .NET float data type.So I checked table in SQL Server Data Types and Their .NET Framework Equivalents on MSDN and found that the SQL float is the equivalent to the .NET double. I tried
SqlDataReader.GetDoubleand was able to retrieve data without error. Since you want a decimal though, you’ll need to cast: