0

I could use some help :( I am trying to get the last generated ID from an identity column in sql and assign it to a variable named ConvId The value has datatype int in sql server, I tried using int to get the value that didnt work and now i tried int32 because i found a conversion table that says that in c# it should be int32 that doesnt work either it keeps giving me this error. system.InvalidCastException below i pasted the code that generates the error please help if possible.

cmd = new SqlCommand();
cmd.CommandText = "SELECT SCOPE_IDENTITY()";
cmd.Connection = con;
Int32 ConvId = (Int32)cmd.ExecuteScalar();
Debug.Print("The last generated id value = " + ConvId);
  • 1
    I'd imagine this is related: [Why does select SCOPE_IDENTITY() return a decimal instead of an integer?](http://stackoverflow.com/questions/2601620/why-does-select-scope-identity-return-a-decimal-instead-of-an-integer) – Charles Mager Sep 30 '16 at 14:45
  • Cast the return value to `decimal`. `SCOPE_IDENTITY` is a decimal – Panagiotis Kanavos Sep 30 '16 at 14:46
  • just tried this and it still gives me the casting error `code` Decimal ConvId = (Decimal)cmd.ExecuteScalar(); `code` – Frederik van Vliet Sep 30 '16 at 15:08
  • Did you try using `var` and stopping the debugging on the line to see the type returned by the sql command? – Eric Wu Sep 30 '16 at 16:24

0 Answers0