c# validating login with sql database

protected void btnLogin_Click(object sender, EventArgs e)
{
    string EmailAddr = "";
    string Password = "";
    string strConn = ConfigurationManager.ConnectionStrings["EPortfolioConnectionString"].ToString();

    SqlConnection conn = new SqlConnection(strConn);

    SqlCommand cmd = new SqlCommand("SELECT * FROM Parent WHERE [EmailAddr]=@EmailAddr AND [Password]=@Password", conn);

    cmd.Parameters.AddWithValue("@EmailAddr", EmailAddr);
    cmd.Parameters.AddWithValue("@Password", Password);

    SqlDataAdapter daParentLogin = new SqlDataAdapter(cmd);
    DataSet result = new DataSet();

    conn.Open();
    daParentLogin.Fill(result, "Login");
    conn.Close();

    if (result.Tables["Login"].Rows.Count > 0)
    {
        lblMessage.Text = "Invalid login credentials";
    }
    else
    {
        Response.Redirect("SubmitViewingRequest.aspx");
    }
}

the codes above doesn't validate the email address and password with the database. any email address and password entered is considered correct. can i get help? thank you!

2 answers

  • answered 2018-07-11 06:38 Krunal Patel

    Change your if condition

    if (result.Tables["Login"].Rows.Count > 0) // For Successfully Login
    {
        Response.Redirect("SubmitViewingRequest.aspx");    
    }
    else // For Invalid User credentials
    {
        lblMessage.Text = "Invalid login credentials";
    }
    

  • answered 2018-07-11 06:48 Zeeshan Adil

    This happens when we mistakenly put if conditions in reverse order. Please change your code with if conditions replaced like this:

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        string EmailAddr = "";
        string Password = "";
        string strConn = ConfigurationManager.ConnectionStrings["EPortfolioConnectionString"].ToString();
    
        SqlConnection conn = new SqlConnection(strConn);
    
        SqlCommand cmd = new SqlCommand("SELECT * FROM Parent WHERE [EmailAddr]=@EmailAddr AND [Password]=@Password", conn);
    
        cmd.Parameters.AddWithValue("@EmailAddr", EmailAddr);
        cmd.Parameters.AddWithValue("@Password", Password);
    
        SqlDataAdapter daParentLogin = new SqlDataAdapter(cmd);
        DataSet result = new DataSet();
    
        conn.Open();
        daParentLogin.Fill(result, "Login");
        conn.Close();
    
        if (result.Tables["Login"].Rows.Count > 0)
        {
              Response.Redirect("SubmitViewingRequest.aspx");
        }
        else
        {
              lblMessage.Text = "Invalid login credentials";
        }
    }
    

    Hope this helps