2

I'm trying to get the max id of the table category using this code

string maxid = "";
string query = "SELECT MAX(Cat_ID) + 1 FROM Category";

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["JokerCafe"].ConnectionString);

try
{
     conn.Open();
     SqlCommand cmd = new SqlCommand(query, conn);
     maxid = cmd.ExecuteNonQuery().ToString();
}
catch (Exception ex)
{
     MessageBox.Show(ex.Message);
}
finally
{
     conn.Close();
}

return maxid;

I run this query in sql it is returning exact value but when try to execute it from code it returns -1. Kindly guide me what's going wrong with it?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
buddy
  • 418
  • 4
  • 10
  • 29

2 Answers2

4

ExecuteNonQuery() will return the affected row count. For example if you are trying to execute any update statement or delete statement through ExecuteNonQuery() method then it will return the number of affected rows.

But, if you want to fetch a value from specific field then you need to try ExecuteScalar() method. It will return Object type value. Using this method you can fetch only a single value record.

object val = command.ExecuteScalar();
if (val != null)
{
   //Do your stuff here.
}
famousgarkin
  • 13,687
  • 5
  • 58
  • 74
Shell
  • 6,818
  • 11
  • 39
  • 70
2

ExecuteScaler is your solution

It executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

so do modify your code to

maxid = cmd.ExecuteScalar().ToString();

or

maxid = cmd.ExecuteScalar() as string; //to be safe side if return value is null

and you'll get the value expected from the query

pushpraj
  • 13,458
  • 3
  • 33
  • 50