Reputation: 683
I am trying to get the result of sql query in an int variable, but I am getting object null reference error. Can someone guide me please.
oconn = new SqlConnection(oSession.CONNECTION_STRING);
oconn.Open();
objCmd.CommandText = "select Rule_Approval_Selection from UserFile where uid=" + intUserID;
int value = (Int32)(objCmd.ExecuteScalar());
oconn.Close();
Upvotes: 1
Views: 215
Reputation: 13
oconn = new SqlConnection(oSession.CONNECTION_STRING);
oconn.Open();
objCmd.CommandText = "select Rule_Approval_Selection from UserFile where uid=" + intUserID;
var x=objCmd.ExecuteScallar();
if (x!= null && DBNull.Value != x)
{
int value = (Int32)(objCmd.ExecuteScalar());
}
oconn.Close();
try this...
Upvotes: 0
Reputation: 726569
ExecuteScalar()
returns null
when the command has no rows. In your case, when intUserId
does not correspond to an existing user, null
would be returned.
Switch to int?
to handle this issue:
int? value = (Int32?)(objCmd.ExecuteScalar());
Now your variable value
would be set to non-null when intUserId
exists in the database; otherwise, it would be null
.
Upvotes: 5