Sumedha Vangury
Sumedha Vangury

Reputation: 683

Error in return value of ExecuteScalar()

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

Answers (2)

user6730095
user6730095

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

Sergey Kalinichenko
Sergey Kalinichenko

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

Related Questions