ExecuteScalar() not returning single field value

  • Thread starter Thread starter cmo63126
  • Start date Start date
C

cmo63126

Why am I not able to retrieve the value of ID (which does exist) using
ExecuteScalar()? Do i simply have to use ExecuteReader() instead?

My problem snippet:

string mySQL = "SELECT ID FROM Table WHERE TableID = 1";
//TableID is a unique ID within Table, no dupiclates-risk

myCommand = new SqlCommand(mySQL, myConn);
myConn.Open();
int myID = (int)myCommand.ExecuteScalar();
myConn.Close();
return myID;

My result:
Object reference not set to an instance of an object.
 
Is there a record with TableID=1 ?

Is the error being generated on the ExecuteScalar() invocation or a
different line?

You might try object obj = myCommand.ExecuteScalar();
and inspect the value of the object or convert it if it is not null.

-Andrew
 
It's not executing the query that is doing it.

You should have the line number that this is failing on: so which line is
it?
 
me = dumbA$$;

the variable I was passing in, unrelated to the simpler example posted
here, was the problem.

my apologies. :(.
 
Back
Top