Avatar of josephdaviskcrm
josephdaviskcrm
Flag for United States of America asked on

C# - What is the return value for SqlCommand.ExecuteScalar?

I've got the following code...

cmd = new SqlCommand(strSQL, conn);
cmd.Connection.Open();
strScalar = cmd.ExecuteScalar();                   <======= Line causing error

What is the return type of the value of this type of command?  Am I using ExecuteScalar() correctly?  How do I make it into a string that will feed into this variable?
.NET ProgrammingC#

Avatar of undefined
Last Comment
Jaime Olivares

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Guy Hengel [angelIII / a3]

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Jaime Olivares

you always have to check if the return value is null or not:
object obj = cmd.ExecuteScalar();
if (obj == null)
{
     // record not found, do something
}
else
{
     // record found, do proper casting like:
     // int x = (int)obj;
     // string s = (string)obj;
}
 
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes