Reputation: 2984
I've got a decimal number for example: -80.63 stored in a field "myvalue". Whenever I'm trying to convert it into a sqldecimal I get the following error:
*Cannot unbox 'myvalue' as a 'System.Data.SqlTypes.SqlDecimal' *
The code is as this:
String MyString = ((SqlDecimal)myvalue).Value.ToString("N");
As I understand decimal it should not be a precision error (it also happens with positive numbers btw). So my question here is: What causes this error?
As it was asked about in a comment: myvalue is part of a datatable (as example DataTable mytable with what is in myvalue being one of the columns values):
foreach (DataRow detail in myDataTable)
{
var myvalue = detail["Sum"];
String MyString = ((SqlDecimal)myvalue).Value.ToString("N");
}
Upvotes: 0
Views: 299
Reputation: 460298
All I see is "object" thanks to the data from the sql being loaded into a datatable.
Then use the DataRow.Field
extension method to get the decimal
value.
For example:
foreach (DataRow detail in myDataTable)
{
decimal myvalue = detail.Field<decimal>("Sum");
string valueToDisplay = myvalue.ToString("N");
}
Note that it even supports nullables, so if the column can contain NULL
s:
foreach (DataRow detail in myDataTable)
{
decimal? myvalue = detail.Field<decimal?>("Sum");
string valueToDisplay = myvalue.HasValue ? myvalue.Value.ToString("N") : "";
}
Upvotes: 1