user3020047
user3020047

Reputation: 888

Specified cast is not valid in vb.net

Getting this error when assigning an integer variable to a value coming back from a SQL stored procedure that may at times contain a NULL.

   System.InvalidCastException: Specified cast is not valid. 

Code snippet:

   Dim iUserId As Nullable(Of Integer)

  ' Get the UserId associated to the server.
  .CommandType = Data.CommandType.StoredProcedure
  .CommandText = "SelectUserIdByServerId"
  .Parameters.Clear()
  .Parameters.AddWithValue("@ServerId", Request("serverid"))

  ' Returns back 1 column.
  iUserId = .ExecuteScalar()

I though that if I have: Dim iUserId As Nullable(Of Integer), that it should not have a problem with it.

Upvotes: 1

Views: 3479

Answers (1)

Magnus
Magnus

Reputation: 46909

ExecuteScalar() returns Object which is an integer or DbNull value.
So you need to write it like this:

Dim tmp As Object = .ExecuteScalar()
iUserId = if(Convert.IsDbNull(tmp), new integer?(), directcast(tmp, integer))

Upvotes: 3

Related Questions