Connecting Login Form In C# With Database For User Type Authentication

Introduction

This article deals with how to create a Windows Form Application in C# as a Login Page which basically all applications contain as the starting page, where users will be validated for their passwords. To validate 'n' number of users who have their username and unique password for their login provided by the Administrator, I have connected the login page with the database which could hold information about the usernames and their corresponding password. The focus is how to connect the form to the database; and based upon the condition, the username and password entered in the database are validated at the time of login entry. I have used Visual Studio 2015 C# Windows Form Application to connect with SQL 2012 Express combined with SQL 2012 Server Management Studio for support. The article is actually a continuation of my previous article without database connection.

Prerequisite
  1. Visual Studio 2015 
  2. SQL 2012 (32-bit or 64-bit) according to your PC's requirement
  3. SQL 2012 Server Management Studio (32-bit or 64-bit) according to your PC's requirement
Let's discuss the steps involved in creating the page.

Step 1

Open Visual Studio 2015 and click on File --> New --> Project which opens up the template window with many developing options.

 

Step 2

In the available options, select Visual C# for which the corresponding developer options are available. In that, select Windows Forms Application and find the field with Name to give the desired name for the application and click OK.

 
 
Step 3

The above step brings in an empty Windows Form where the user can use Tools for designing the empty form into interactive form. I have used Label (4 nos), TextBox (2 nos), Button (2 nos), and a PictureBox. Placing the tools in the right designing way, it looks like the below image.
 
 
 
Step 4

The first three labels have been used only for display purposes, and the last label which I have kept to display information regarding the attempts available for the user in case the user has entered the wrong credentials (either wrong user name or wrong password). I have placed the label under the PictureBox and for coding recognition, I have named it as lbl_Msg in label properties. 
             
 
Step 5

The conventional way of any login form will contain password displayed in a special character which is for security purposes. To bring that concept into your login form, select the Properties option of TextBox in which you could find the option Password Char where you can give your desired special character (in my case, I have used * asterisk). By making this change, if you run your application, it will display only the special symbol when you enter a password.
             
 Step 6

Now, it is time for creating the repository for your login form. For this, go to Start menu and find the SQL Server Management Studio and click once to open. It is available for me because I have installed SQL 2012 and SQL Server Management Studio in my PC.

 
Step 7

After clicking the Management Studio, the SQL Server 2012 opens up in a new window. You will be provided with information on the starting page with Server Name and the type of Authenticaiton that you will be using. Server Name is the default one and for Authenticaiton, I have chosen Windows Authentication for connecting with my form. After this basic step, click Connect option.

 
 
Step 8

After clicking on Connect, a new window opens up where you can find Object Explorer option on left side of the window. Try to find the option Databases, right-click on it, and click on "New Database..." option for creating your database.

 
 
Step 9

After selecting New Database, a new window opens up where you have to give a name for your database in Database name field. After giving the desired name, click OK.

 
 
Step 10

After clicking OK, you could find your database displayed under Databases option in Object Explorer. Here, I have named my database as login which in-turn lists down the available options with it. To store my credentials in a table, I find the option called Tables on which I right-click and select the option New Table... 

Step 11

After clicking New Table option a window displays a grid of rows and columns where you have to enter the login and password credentials with their data types. Column Name contains the user name with Data Type of varchar (50) value and move to second Column Name as password with data type of varchar (50).



By doing the above step you create a repository of user name and password fields in which now you are supposed to enter the values under the corresponding fields. For this go to Tables and list it down and you can find the latest table created. Right-click on it and select the option Edit Top 200 Rows which enables you to enter the values. You can enter the credentials here for the number of logins you have in your mind. Here I have added two types like Admin login with its password and User1 with its password.                 

 
Step 12

Its time to make our login form work by putting the logic code inside it.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9. using System.Windows.Forms;  
  10. using System.Data.SqlClient;  
  11.   
  12.   
  13. namespace mylogin  
  14. {  
  15.     public partial class Form1 : Form  
  16.     {  
  17.         static int attempt = 3;  
  18.         public Form1()  
  19.         {  
  20.             InitializeComponent();  
  21.             pictureBox1.Image = new Bitmap(@"C:\Users\Mic 18\Documents\Visual Studio 2015\Projects\mylogin\images1.jpg");  
  22.         }  
  23.   
  24.         private void button2_Click(object sender, EventArgs e)  
  25.         {  
  26.             this.Close();  
  27.         }  
  28.   
  29.         private void login_Click(object sender, EventArgs e)  
  30.         {  
  31.             if(attempt==0)  
  32.             {  
  33.                 lbl_Msg.Text = ("ALL 3 ATTEMPTS HAVE FAILED - CONTACT ADMIN");  
  34.                 return;  
  35.             }  
  36.             SqlConnection scn = new SqlConnection();  
  37.             scn.ConnectionString = @"Data Source=DESKTOP-QTMTID2\SQLEXPRESS;Initial Catalog=login_database;database=login;integrated security=SSPI";  
  38.             SqlCommand scmd = new SqlCommand("select count (*) as cnt from login_database where username=@usr and password=@pwd", scn);  
  39.             scmd.Parameters.Clear();  
  40.             scmd.Parameters.AddWithValue("@usr", txt_UserName.Text);  
  41.             scmd.Parameters.AddWithValue("@pwd", txt_PWD.Text);  
  42.             scn.Open();  
  43.               
  44.             if(scmd.ExecuteScalar().ToString()=="1")  
  45.             {  
  46.                 pictureBox1.Image = new Bitmap(@"C:\Users\Mic 18\Documents\Visual Studio 2015\Projects\mylogin\granted.png");  
  47.                 MessageBox.Show("YOU ARE GRANTED WITH ACCESS");  
  48.             }  
  49.               
  50.             else  
  51.             {  
  52.                   
  53.                 pictureBox1.Image = new Bitmap(@"C:\Users\Mic 18\Documents\Visual Studio 2015\Projects\mylogin\denied.jpg");  
  54.                 MessageBox.Show("YOU ARE NOT GRANTED WITH ACCESS");  
  55.                 lbl_Msg.Text = ("You Have Only " + Convert.ToString(attempt) + " Attempt Left To Try");  
  56.                 --attempt;  
  57.                 txt_UserName.Clear();  
  58.                 txt_PWD.Clear();  
  59.             }  
  60.             scn.Close();  
  61.                                     
  62.            }  
  63.     }  
  64. }  
Step 13

After the coding part with no errors, when you run the application it will appear as the below picture. Any user who has to enter into the application has to enter the correct credentials and those get validated with the database created by you. I have entered the correct value given in the database and click LOGIN.

 
Step 14

This is how the correct credentials get validated with the database values and the logger will be displayed with the below result and a message box to proceed further on. 

 
Step 15

To do a test, I have entered the right user name in USER NAME field but intentionally given the wrong password. When you click LOGIN the below appearance is what the logger gets as information.

 
 
Step 16

Since every logger has to be given a chance to enter the correct credentials, I have cleared the USER NAME and PASSWORD text field area for re-entry and our label comes in handy for displaying the information of how many attempts are left for the user.

 
Step 17

Since all attempts have failed, user is given with visual information from label that the user has lost all attempts for login and has to contact the administrator for getting the right password. 

 
 
Conclusion

The above article is to make the login form more professional in authenticating and validating which will reveal the true value of your main applicaiton that you will create as a big picture. The article throws light on how to use back-end database effectively by connecting it with our front-end application, in our case is a simple login form.

Up Next
    Ebook Download
    View all
    Learn
    View all