Kamil Zahid

Kamil Zahid

  • NA
  • 6
  • 22.6k

Create Login Form on C#

Mar 21 2011 9:53 AM
Hi Guys

This is the code i have used on C# to create a login form and it always prompts me with "Invalid username or password" even though my database holds the correct username and password. Please help???

  private void button1_Click(object sender, EventArgs e)
        {
            string username = textBox1.Text;
            string password = textBox2.Text;

            if (ValidateUserNamePassword(username, password))
            {
                MessageBox.Show("Login successful");
               
            }
            else
            {
                MessageBox.Show("Invalid user name or password");
                return;
            }
        }

        public bool ValidateUserNamePassword(string username, string password)
        {

            MySqlConnection cn = new MySqlConnection(@"SERVER=localhost;" + "DATABASE=clientmanagement;" + "UID=root;" + "PASSWORD=qwerty;");
            {
                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = cn;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "tsp_GetUserNameAndPassword";

                MySqlParameterCollection sqlParams = cmd.Parameters;
                sqlParams.AddWithValue("@UserName", username);
                sqlParams.AddWithValue("@Password", password);

                cn.Open();
                MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);
                if (dr.Read())
                {
                    // this will return true if a row matching the username and password is found.
                    // this means that the user's input is valid
                    return true;
                }
                else
                {
                    return false;
                }

                dr.Close();
                cn.Close();
               
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

Answers (7)