Windows Forms: Create Login Form with MySQL in C#

By FoxLearn 6/1/2017 10:13:29 PM   6.24K
How to Create a Login Window with My SQL in C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "LoginMySql" and then click OK

login mysql c#Step 2: Design your login form as below

login form in c#

Step 3: Create a user table, then add the user table to your dataset as below

dataset in c#

Step 4: Add a click event handler to the button

using System;
using System.Windows.Forms;

namespace LoginMySql
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void txtUsername_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                txtPassword.Focus();
        }

        private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                btnLogin.PerformClick();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUsername.Text))
            {
                MessageBox.Show("Please enter your username.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUsername.Focus();
                return;
            }
            try
            {
                //Get data from user table
                AppDataTableAdapters.usersTableAdapter user = new AppDataTableAdapters.usersTableAdapter();
                AppData.usersDataTable dt = user.Login(txtUsername.Text, txtPassword.Text);
                //Check user exists
                if (dt.Rows.Count > 0)
                {
                    MessageBox.Show("You have been successfully logged in.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //Process your login here
                }
                else
                    MessageBox.Show("Your username or password is incorrect.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

VIDEO TUTORIALS