Sunday, October 18, 2015

Creating Database Driven Login Form Using C# & MySQL


Codes


namespace MyProject

{
    public partial class frmMyLogin : Form
    {
        public frmMyLogin()
        {
            InitializeComponent();
        }

        MySqlConnection con = new MySqlConnection(@"server=localhost;user id=root;database=employee");
        MySqlDataAdapter da = new MySqlDataAdapter();
        MySqlCommand cmd = new MySqlCommand();

        private void btnLogin_Click(object sender, EventArgs e)
        {
            con.Open();
            string Username = txtUsername.Text;
            string Password = txtPassword.Text;

            MySqlCommand cmd = new MySqlCommand("Select UserName,Password from login where UserName='"+txtUsername.Text+"'and Password='"+txtPassword.Text+"'",con);

            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);


            if (dt.Rows.Count > 0)
            {
                MessageBox.Show("Login Sucessfull");
                frmMain mymain = new frmMain();
                mymain.Show();
                this.Hide();
            }

            else
            {
                MessageBox.Show("Invalid UserName or Password");
            }
            con.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult s = MessageBox.Show("Are you sure do you want to exit", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (s == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void btnNewUser_Click(object sender, EventArgs e)
        {       
            string cmdText = "INSERT INTO login(UserName,Password) VALUES (@UserName, @Password)";
            con.Open();
            MySqlCommand cmd = new MySqlCommand(cmdText, con);
            cmd.Parameters.AddWithValue("@UserName", txtUsername.Text);
            cmd.Parameters.AddWithValue("@Password", txtPassword.Text);
           cmd.ExecuteNonQuery();
            MessageBox.Show("Create new user is successful");
            con.Close();
        }
    }
}

 
------------
By Thissa 
----------------