ExecuteScalar() Question

  • Thread starter Thread starter Beringer
  • Start date Start date
B

Beringer

Can someone tell me why I get a run time exception of "Invalid Cast" on the
following code sample on the second line?:

SqlCommand identity = new SqlCommand("SELECT @@Identity", conn);
int temp = (int)(identity.ExecuteScalar());



I Looked in the sample code that somes with VS and this cast method is used
in an example provided by MS (page title "Executing a Data Command that
Returns a Single Value"). If temp is an object and not int, the code works
and you can see the integer value in the debugger.

BTW: the Select command is supposed to return the identity value of the
last inserted record. And I found this at the "CodeGuru" in an article
written by Karl Moore
(www.developer.com/net/net/article.php/11087_2201321_2).



Thank you in advance,

Eric
 
The object returned by your call to ExecuteScalar is of type Decimal. You
can use Convert.ToInt32 instead of just casting, or you can change the type
of your temp variable to Decimal.

Regards, Jakob.
 
Back
Top