开发者

ASP.NET: What is DataReader return type if my sql data type is float?

开发者 https://www.devze.com 2023-03-13 05:57 出处:网络
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

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(rea开发者_StackOverflowder["Price"]);


The return type for reader["Price"] is object. To do what you're trying to do use this:

price = decimal.Parse(reader["Price"].ToString()); 

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.GetDecimal because 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 use SqlDataReader.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.GetDouble and was able to retrieve data without error. Since you want a decimal though, you'll need to cast:

price = (decimal)reader.GetDouble(reader.GetOrdinal("Price"));


decimal.Parse expects string as a parameter. It parses decimal out of string.

reader["Price"] is object, while the real type underneath this object will be float.

The reason why it fail is because it cannot cast object to string.

So you could do

var price = Convert.ToDecimal(reader["Price"]);

or

var price = (float)reader["Price"];

if you know for sure that you type is float.


An SQL Float is a Double in C#. Check out the documentation. http://msdn.microsoft.com/en-us/library/ms131092.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号