Prob something im overlooking but this problem has annoyed me greatly.
im trying to get a value from a dataset and then use it to do some calculations.
in the dataset its seen as an object, so i need to cast it to an int or double.
For some reason im getting a stupid error thats getting on my nerves. heres the code.
private void SpendsAnalysis()
{
float tempQty = 0;
float tempPrice = 0;
double tempTot = 0;
double total = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
tempQty = (float)row.Cells["Qty"].Value;
tempPrice = (float)row.Cells["Unit"].Value;
tempTot = tempQty * tempPrice;
total += tempTot;
}
textBox7.Text = total.ToString();
}
Thrown: “Specified cast is not valid.” (System.InvalidCastException)
when casting form a number, must be less than inifnite. This is the annoying error im getting. now i get the data from my dataset, which gets its data from a stored procedure.
I believe the “Qty” field type is currency(yeh, why is qty currency haha, not my tables!). in my datagrid view it looks like 1.000, is this due to a type conversion? how would i rectify this?
Many Thanks in Advance!
A type cast has to succeed, and unfortunately, casting directly from an
objectto a different type than the underlying object is not going to work, even if casting from adecimal(the .NET type forcurrency) to afloatwould normally work.If the type in the database is
currency, I would try this:or, you can use this:
which will take a look at the actual value and figure out the right type of conversion to perform.
To answer your comment, the above expression involves two distinct conversions:
objectto a value-type, in this case to adecimaldecimaltofloatThe first, the unboxing conversion, is documented in the C# language specification section 4.3.2 (this is the C# 4.0 specification):
(my emphasis)
I also have the annotated version of the specification, and Eric Lippert summarizes this as:
The second, the explicit conversion, is documented in the C# language specification section 6.2.1:
(again, my emphasis)
To summarize:
objectto a value-type, you’re actually unboxing the boxed value, and you first have to unbox the actual underlying value into its correct type, before you can convert it to a different type.