parish parab
parish parab

Reputation: 71

Must declare the scalar variable "@username". How to overcome it

I am having problem with my code Always having the error which i am not understanding. Please help with my code i want to retrieve the user details from the db for login page

 string uname = TextBox1.Text.Trim();
        string pass = TextBox2.Text.Trim();
        try
        {
            con.Open();
            string query = "SELECT user_name, user_password FROM [user] where user_name=@username and user_password=@password";
            cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = uname;
            cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = pass;
            cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
            rd = cmd.ExecuteReader();
            if (rd.HasRows)
            {
                Response.Write("Login successful");

            }
            else
            {
                Response.Write("login Unsucessful");
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            con.Close();
        }
    }    

Upvotes: 0

Views: 1365

Answers (1)

Jacob Lambert
Jacob Lambert

Reputation: 7679

You need to create your cmd prior to adding the paramaters. Your code should look like:

        con.Open();
        string query = "SELECT user_name, user_password FROM [user] where user_name=@username and user_password=@password";
        cmd = new SqlCommand(query, con);
        cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = uname;
        cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = pass;

EDIT: and as @ekad said, you do not need cmd.ExecuteNonQuery();

Upvotes: 5

Related Questions