0

Can anyone perhaps tell me why is my session value returning a -1 when saving to the database based on this btn Click event.

       using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmdManID = new SqlCommand("SELECT 
        managerID,userEmailAddress,userName FROM [MANAGER] ,[USER] WHERE 
        [MANAGER].managerID = [USER].userID AND [USER].userName= @Uname;",con);
        cmdManID.Parameters.Add(new SqlParameter("@Uname", 
        Session["UName"]));

        con.Open();
    }

        int manID = cmdManID.ExecuteNonQuery();

        //manID;



        con.Close();
0

1 Answer 1

2

Because -1 is exactly the result you should expect on a SELECT from ExecuteNonQuery:

"For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1."

https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executenonquery?view=netframework-4.7.2

If you only expect a single return value, that is what ExecuteScalar is for: https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar?view=netframework-4.7.2

Sign up to request clarification or add additional context in comments.

2 Comments

Doh! Good catch ;)
@Christopher thank you so much I used the ExecuteScaler and it works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.