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?
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.
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments