Hi,
Can anybody help me how to convert type object ionto decimal please?
I have this code
object rez = command2.ExecuteScalar();
iznosd = (decimal)rez;
I tried also
iznosd = (decimal)command2.ExecuteScalar();
but nothing changed, I get error "Specified cast is not valid error" in this line
iznosd = (decimal)command2.ExecuteScalar();
Thanks
Loading

Santhosh Kumar JayaramanRank #563 · 4.3K reputationPosted Jul 10, 2012, 3:52 AM EDT
VulpesRank #55 · 29.2K reputationPosted Jul 10, 2012, 4:01 AM EDT
If so, then you need to cast to the actual type first and then cast to decimal. For example, if it's a double:
object rez = command2.ExecuteScalar();
iznosd = (decimal)(double)rez;
This should also work:
Decimal.TryParse(command2.ExecuteScalar().ToString(), out iznosd);
Jignesh TrivediRank #16 · 50.3K reputationPosted Jul 10, 2012, 4:09 AM EDT
hi Nel,
Santhosh is right, if your ExecuteScalre may return null and direct cast cannot handle null.
and Convert.ToDecimal can handle Null.
decimal? iznosd = Convert.ToDecimal(command2.ExecuteScalar());
hope this will help you.
VulpesRank #55 · 29.2K reputationPosted Jul 10, 2012, 4:45 AM EDT
NelRank #2,060 · 702 reputationPosted Jul 10, 2012, 10:37 PM EDT