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 JayaramanPosted Jul 10, 2012, 7:52 AM
NelPosted Jul 11, 2012, 2:37 AM
VulpesPosted Jul 10, 2012, 8:45 AM
Jignesh TrivediPosted Jul 10, 2012, 8:09 AM
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.
VulpesPosted Jul 10, 2012, 8:01 AM
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);