How to compare the stored procedure's output in C#?

I want to check first if the user exists or not so I made a stored procedure in my mssql file to check that.

CREATE PROCEDURE Login
@username varchar(20),@password varchar(20),
@status int output
as
if exists (select username , password from SystemUser where username=@username and password=@password)
set @status = 1
else
set @status= 0

then, using asp.net webforms I’m creating a login page for the users

  protected void login(object sender, EventArgs e)
        {
            String connstr = WebConfigurationManager.ConnectionStrings["Sports"].ToString();
            SqlConnection conn = new SqlConnection(connstr);
            
            String username = txt_Username.Text;
            String password = txt_password.Text;
            SqlCommand login = new SqlCommand("userLogin", conn);
            login.CommandType = CommandType.StoredProcedure;
            login.Parameters.Add(new SqlParameter("@username", username));
            login.Parameters.Add(new SqlParameter("@password", password));
            SqlParameter loginstatus = login.Parameters.Add("@status", SqlDbType.Int);
            loginstatus.Direction = ParameterDirection.Output;
            conn.Open();
            login.ExecuteNonQuery();
            conn.Close();
            if (loginstatus.GetInt32 == 1)
            {
                Response.Write("hello");
                Response.Redirect("Home.aspx");
            }
        }

Error CS1061 ‘SqlParameter’ does not contain a definition for ‘GetInt32’ and no accessible extension method ‘GetInt32’ accepting a first argument of type ‘SqlParameter’ could be found (are you missing a using directive or an assembly reference?)
any idea how can I compare the output from the stored procedure in the if condition ?
Thanks in advance,

tried different types of methods like .value.
expecting to know how to compare the value to an int.

>Solution :

you can get the value using .Value

if ((int)loginstatus.Value == 1)
{
    ...
}

There are other issues also in your code.

you are storing the password as plain text in a database table.

please use using with SqlConnection to dispose of automatically, same comment for SqlCommand .

and please use meaningful names when declaring variables like SqlCommand login. it’s very unclear by the name login. it should be command or sqlCommand

Leave a Reply