ExecuteScalar returns null if the request was not returned (for example, when the SearchForPassenger stored procedure SearchForPassenger not return rows).
So this line:
item = (int) command.ExecuteScalar();
I am trying to use null for int in this case. This will raise a NullReferenceException .
By mark the answer that just appeared, you need to check for null :
object o = command.ExecuteScalar(); item = o == null ? 0 : (int)o;
source share