Windows Forms: Create Metro Login Form with SQL Database in C#

How to create a Metro login form with SQL Database using Metro Framework, Dapper ORM in C#

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

metro login form

Step 2: Right click on your project select Manage NuGet Packages -> Search metro framework, dapper -> Install

Dapper is a high performance Micro-ORM supporting SQL Server, MySQL, Sqlite, SqlCE, Firebird etc..

install metro framework

If you don't see the metro framework in your toolbox, you can view How to download and install metro framework

Step 3: Design metro login form as below

metro login form

Step 4: Create a user class to map data return from sql server

public class User
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

You can copy below the sql script to create a new database

USE [master]
GO
CREATE DATABASE [dbuser]
 CONTAINMENT = NONE
 ON  PRIMARY 
( NAME = N'dbuser', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\dbuser.mdf' , SIZE = 4096KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'dbuser_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\dbuser_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)

Create a user table

CREATE TABLE [dbo].[Users](
	[UserName] [varchar](25) NOT NULL,
	[Password] [varchar](50) NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
	[UserName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Step 5: Add a connection string to the App.config file

  <connectionStrings>
    <add name="cn" connectionString="Data Source=.;Initial Catalog=dbuser;User ID=sa;Password=123@qaz;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

You can easily change your connection string in the App.config file without recompiling your source code

Step 6: Create UserName, Password, RememberMe properties with user scope in the settings tab

create user settings

Step 7: Add code to Form_Load event

private void frmLogin_Load(object sender, EventArgs e)
{
    //Init metro theme, style
    this.StyleManager = metroStyleManager1;
    metroStyleManager1.Theme = MetroFramework.MetroThemeStyle.Light;
    metroStyleManager1.Style = MetroFramework.MetroColorStyle.Green;
    if (Properties.Settings.Default.RememberMe)//True
    {
        //Set value to username textbox and password textbox
        txtUserName.Text = Properties.Settings.Default.UserName;
        txtPassword.Text = Properties.Settings.Default.Password;
    }
}

Step 8: Add code to handle Login button

private void btnLogin_Click(object sender, EventArgs e)
{
    //Check username is null or empty
    if (string.IsNullOrEmpty(txtUserName.Text))
    {
        MetroFramework.MetroMessageBox.Show(this, "Please enter your username.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        txtUserName.Focus();
        return;
    }
    try
    {
        using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
        {
            if (db.State == ConnectionState.Closed)
                db.Open();
            //Excute sql query, then map data return from sql to User class
            User obj = db.Query<User>($"select *from Users where UserName = '{txtUserName.Text}'", commandType: CommandType.Text).SingleOrDefault();
            if (obj != null)
            {
                if (obj.Password == txtPassword.Text)//True
                {
                    using (frmMain frm = new frmMain())//Open main form and hide login form
                    {
                        this.Hide();
                        frm.ShowDialog();
                    }
                }
                else
                    MetroFramework.MetroMessageBox.Show(this, "Your username and password don't match.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
                MetroFramework.MetroMessageBox.Show(this, "Your username and password don't match.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
    catch (Exception ex)
    {
        MetroFramework.MetroMessageBox.Show(this, ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Step 9: Add code to handle RememberMe checkbox

private void chkRememberMe_CheckedChanged(object sender, EventArgs e)
{
    if (chkRememberMe.Checked)//Set value to user settings
    {
        Properties.Settings.Default.UserName = txtUserName.Text;
        Properties.Settings.Default.Password = txtPassword.Text;
    }
    else
    {
        Properties.Settings.Default.UserName = null;
        Properties.Settings.Default.Password = null;
    }
    Properties.Settings.Default.RememberMe = chkRememberMe.Checked;
    Properties.Settings.Default.Save();//Save data to user settings
}

VIDEO TUTORIALS

 

Related Posts