Advertisement

header ads

How to Create a Login Window with user Authentication using C#

In this post I'm going to tell you how to create a login form with user authentication. If you are creating a program for a commercial purpose it is very important to have user authentication in the login window.


That means if the Admin logged into the system from using admins password, Admin can get the administrator privileges out of the program. and if a user logged in to the system. the user gets user privileges.

Here is the video of creating the Login window. Here I'm using visual studio 2012 for this project


Here is the code of the Login form



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

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

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection sc = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\Users\RD computer\Documents\database.mdf';Integrated Security=True;Connect Timeout=30;");
            SqlDataAdapter sda = new SqlDataAdapter("Select Role From Login Where Username ='"+textBox1.Text+"' and Password ='"+textBox2.Text+"'",sc);
            DataTable dt = new DataTable();
            sda.Fill(dt);

            if (dt.Rows.Count == 1 && dt.Rows[0][0].ToString() == "Admin") {
                MessageBox.Show("You are logged in as Admin!");
            }
            else if (dt.Rows.Count == 1 && dt.Rows[0][0].ToString() == "User")
            {
                MessageBox.Show("You are logged in as User!");
            }
            else {
                MessageBox.Show("Please check your Username or Password!");
            }
        }
    }
}

here is the SQL database code 



1
2
3
4
5
6
CREATE TABLE [dbo].[Login] (
    [Username] NVARCHAR (50) NOT NULL,
    [Password] NVARCHAR (50) NULL,
    [Role]     NVARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Username] ASC)
);


If you have any questions feel free to comment them down below. and subscribe to my youtube channel and share this post and like out facebook page.


Post a Comment

0 Comments