Introduction
Hello guys, in this article we will create a login and registration form with a database in a C# Windows Form application. This application has three forms, login, registration, and home. Users first register themselves, then log in to their account and see the welcome message on the home page.
Step 1
Open your visual studio, here I will use Visual Studio 2019.
Step 2
The clock on file menu on top of the visual studio, hover mouse on new, and click on Project.

Step 3
Search for Windows Form App (.NET framework) and click on next.

Step 4
In this step, you have to enter some details of your application and then click on the Create button. You have to enter the following details:
- Project Name: Name of your project
- Location: Location where you want to store your app on your local computer.
- Solution Name: This name is displayed in solution explorer in visual studio.
- Framework: Select the appropriate framework as per your application requirements.

Step 5
Now your project is created. Open Solution Explorer. If you don’t see solution explorer, you can open it from the View menu on top, or you can try the short cut key “Ctrl+W,S”. We need to create some pages for our application. Right-click on the solution name then Hover the mouse on Add and click on Add New Item, or you can user short cut key “Ctrl+Shift+A”.

Step 6
Now you see a dialog where we add our forms. Select Windows Form, give it a proper name and click on Add. Add a Login, Registration, and Home page in the same way.

Step 7
Now we need to add a database in our project. Right-click on the solution name, then Hover mouse on Add and click on Add New Item, or you can user short cut key “Ctrl+Shift+A”. Select data filter from the left sidebar to see the item which is associated with the database. Select service-based database, give it a name and click on add.

Step 8
Now we create a table that we user in login and registration. Double click on the database file from solution explorer. It will open a database file in the server explorer.
Expand your database and right-click on the table, then click on Add New Table.

Step 9
Create a table field that you want. Here, I added only three fields, ID, Username, and password, where ID is auto incremented by 1. You can set it by right clicking on the field name, click on property, and find the Id Identity Specification. Expand it and make it true (Is Identity) field and give an increment number which increments Id by adding this number in the last Id.
q
CREATE TABLE [dbo].[LoginTable]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[username] NVARCHAR(50) NULL,
[password] NVARCHAR(50) NULL
)
Step 10
Now we create a Registration form. Create a design for your form as you need. In the below image, you see how I design a form.

Step 11
Now click anywhere on the form. It will generate a Form_Load event where you can enter the following code. This code creates a database connection and opens it. In the next step, you will learn how you get that connection string which are added in SQLConnection Constructor.
private void Registration_Load(object sender, EventArgs e)
{
cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=H:\Website\RegistrationAndLogin\Database.mdf;Integrated Security=True");
cn.Open();
}
Step 12
Go to Server Explorer, right-click on the database, then click on Modify Connection.

Step 13
Now you see a windows dialog popup click on the advance button. This will open another dialog. Before that, click on the test button and check that your database is working properly.

Step 14
Copy the path which shows below on this dialog and close both dialogs. Then paste this path in the form load event. Add @ sign before this path so there's no need to change the slash.

Step 15
We need to open the login page when the user clicks on the login button, so enter the following code in the Login Button click event.
private void Button1_Click(object sender, EventArgs e)
{
this.Hide();
Login login = new Login();
login.ShowDialog();
}
Code Explanation
- First, we hide the current form which is registration .
- Then we create an object of login page and show login form using that object.
Step 16
Now add the following code in the registration button click event:
private void BtnRegister_Click(object sender, EventArgs e)
{
if (txtconfirmpassword.Text != string.Empty || txtpassword.Text != string.Empty || txtusername.Text != string.Empty)
{
if (txtpassword.Text == txtconfirmpassword.Text)
{
cmd = new SqlCommand("select * from LoginTable where username='" + txtusername.Text + "'", cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
cmd = new SqlCommand("insert into LoginTable values(@username,@password)", cn);
cmd.Parameters.AddWithValue("username", txtusername.Text);
cmd.Parameters.AddWithValue("password", txtpassword.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Your Account is created . Please login now.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("Please enter both password same ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please enter value in all field.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Code Explanation
- First of all, we check that the user entered a value in all fields. If yes, then continue, otherwise, show a message using the message box.
- Then we check if the password and confirm password both are the same.
- Then we check if any record/user is already registered with that username if not then continue further otherwise show an error message.
- In last we insert data in the table using the SQLCommand object.
Step 17
Now we create a login page. Here, I added two text boxes for username and password and two buttons for a login and open registration form.

Step 18
Click on anywhere in a form which generates a Form_Load event add connection code, as shown below.
private void Login_Load(object sender, EventArgs e)
{
cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=H:\Website\RegistrationAndLogin\Database.mdf;Integrated Security=True");
cn.Open();
}
Step 19
On a Registration button click, add the following code which opens the registration form.
private void Btnregister_Click(object sender, EventArgs e)
{
this.Hide();
Registration registration = new Registration();
registration.ShowDialog();
}
Step 20
Add the below code in the login button click for redirecting users to the home page form if the user exists.
private void BtnLogin_Click(object sender, EventArgs e)
{
if (txtpassword.Text != string.Empty || txtusername.Text != string.Empty)
{
cmd = new SqlCommand("select * from LoginTable where username='" + txtusername.Text + "' and password='"+txtpassword.Text+"'", cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
this.Hide();
Home home = new Home();
home.ShowDialog();
}
else
{
dr.Close();
MessageBox.Show("No Account avilable with this username and password ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please enter value in all field.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Code Explanation
- Here, first of all, we check if the user enters a value in both fields. If yes, then continue, otherwise, show an error message.
- Then we check if the user exists in our database with that username and password. If the user exists, then open the home page which we generated at the start.
Step 21
Change the start page as login in Program.cs File.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
Step 22
Now run your application.



Login.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RegistrationAndLogin
{
public partial class Login : Form
{
SqlCommand cmd;
SqlConnection cn;
SqlDataReader dr;
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Articles\Code\RegistrationAndLogin\Database.mdf;Integrated Security=True");
cn.Open();
}
private void Btnregister_Click(object sender, EventArgs e)
{
this.Hide();
Registration registration = new Registration();
registration.ShowDialog();
}
private void BtnLogin_Click(object sender, EventArgs e)
{
if (txtpassword.Text != string.Empty || txtusername.Text != string.Empty)
{
cmd = new SqlCommand("select * from LoginTable where username='" + txtusername.Text + "' and password='"+txtpassword.Text+"'", cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
this.Hide();
Home home = new Home();
home.ShowDialog();
}
else
{
dr.Close();
MessageBox.Show("No Account avilable with this username and password ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please enter value in all field.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
Registration.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RegistrationAndLogin
{
public partial class Registration : Form
{
SqlCommand cmd;
SqlConnection cn;
SqlDataReader dr;
public Registration()
{
InitializeComponent();
}
private void Registration_Load(object sender, EventArgs e)
{
cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Articles\Code\RegistrationAndLogin\Database.mdf;Integrated Security=True");
cn.Open();
}
private void BtnRegister_Click(object sender, EventArgs e)
{
if (txtconfirmpassword.Text != string.Empty || txtpassword.Text != string.Empty || txtusername.Text != string.Empty)
{
if (txtpassword.Text == txtconfirmpassword.Text)
{
cmd = new SqlCommand("select * from LoginTable where username='" + txtusername.Text + "'", cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
cmd = new SqlCommand("insert into LoginTable values(@username,@password)", cn);
cmd.Parameters.AddWithValue("username", txtusername.Text);
cmd.Parameters.AddWithValue("password", txtpassword.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Your Account is created . Please login now.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("Please enter both password same ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please enter value in all field.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Button1_Click(object sender, EventArgs e)
{
this.Hide();
Login login = new Login();
login.ShowDialog();
}
}
}
Home.cs
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;
namespace RegistrationAndLogin
{
public partial class Home : Form
{
public Home()
{
InitializeComponent();
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RegistrationAndLogin
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
}
}
Conclusion
So here, we created a simple login and registration page in a Windows Form application. I hope you liked this article, share it with your friends.

Elena DragPosted Apr 21, 2023, 2:09 PM
Thanks, I've encountered a lot of writing codes for registration and login and far now this is the clearest way to me.
bing bongPosted Dec 2, 2022, 11:58 AM
I agree with Francisco, this absolutley sucks. Haven't even declared any of the variables so the program can't execute anything properly!! Such a waste of time
Francisco CastilloPosted Dec 1, 2022, 3:59 AM
This tutorial sucks, it's incomplete and even if you download the source code it doesn't work
Kriscelle LeañoPosted May 17, 2022, 5:57 AM
Why i have an error in cn, cmd, dr, sqlcommand?
lisa rossPosted Mar 28, 2022, 8:33 PM
Now im getting lock errors again
lisa rossPosted Mar 28, 2022, 8:08 PM
What is wrong with your code? the datbase is connected good but when i run the app the db disconnects
lisa rossPosted Mar 28, 2022, 8:04 PM
Now i have an object error for executereader why?
lisa rossPosted Mar 28, 2022, 8:04 PM
This exception was originally thrown at this call stack: [External Code] RegistrationAndLogin.Registration.BtnRegister_Click(object, System.EventArgs) in Registration.cs [External Code] RegistrationAndLogin.Login.Btnregister_Click(object, System.EventArgs) in Login.cs [External Code]
lisa rossPosted Mar 28, 2022, 8:02 PM
Why i am getting these erros? i cant save the database no matter how many times i try
lisa rossPosted Mar 28, 2022, 7:57 PM
Wwhat is this error invalid logon table? lisa
lisa rossPosted Mar 28, 2022, 7:56 PM
I just started a new project but i keep getting invalid object login table
lisa rossPosted Mar 28, 2022, 7:46 PM
Why am i getting this errpor?
lisa rossPosted Mar 28, 2022, 7:46 PM
The file is locked by: "RegistrationAndLogin (4808), RegistrationAndLogin (15116)"
lisa rossPosted Mar 28, 2022, 7:28 PM
I cant run the file now it says file is locked why? Lisa
lisa rossPosted Mar 28, 2022, 7:10 PM
I connected my same db from my own code that i follwed but when i try to register i get an error Lisa
lisa rossPosted Mar 28, 2022, 6:57 PM
Wait i h=just found your zip code file ; i am trying to fix the db cuz in my code the db works but i dont have th ehome.cs ; i will try to fix Lisa
lisa rossPosted Mar 28, 2022, 6:49 PM
Like i mean the zip file for VS? cuz your instructions are not always clear sorry and you didnt give the code for the home.cs and the name.ca files thank you Lisa
lisa rossPosted Mar 28, 2022, 6:49 PM
Can you actually provide your source code?
lisa rossPosted Mar 28, 2022, 6:48 PM
Hello sir are you there? Lisa
lisa rossPosted Mar 28, 2022, 6:45 PM
Hello where is the code for the home.cs? this is incomplte
Daniel DanielPosted Jan 21, 2022, 1:26 PM
Hello Sir. Great work. I try to recreate your work and downloaded your zip. I always get the same Exception. Maybe you can help me with that i already searched for a solution online. https://gyazo.com/788040580efd7bd9781ad11901c64298
shiv ghargePosted Jan 17, 2022, 12:56 PM
Sir i got one error while I was running my code. I was registering myself to create account,the expected output was "account created successfully" But i got exception unhandled, how to resolve it?? Need help.
Robert EverettPosted Dec 4, 2021, 3:51 PM
This is great, but what if I want to use modern technologies ? For example, Entity Framework 6, LINQ to SQL, etc ?
green gamingPosted Nov 29, 2021, 3:10 PM
System.InvalidOperationException: 'ExecuteReader requires an open and available Connection. The connection's current state is closed.'
Aisya AtiqahPosted Jun 26, 2021, 10:00 AM
Why my cn open was error? i already run your coding
Karl LinganPosted Jun 6, 2021, 10:17 AM
I have a question. In Step 17, when creating a new login page. Should the login page be created in Form1? or you should create another windows form instead of using form1?
Karl LinganPosted Jun 6, 2021, 9:09 AM
System.InvalidOperationException: 'ExecuteReader: Connection property has not been initialized.' How do I solve this?
Karl LinganPosted Jun 6, 2021, 8:48 AM
How do I solve the problem 'Keyword not supported: 'datasource'.' and it shows that it is an exception thrown. Please tell me how to solve it
Banana GamingPosted May 28, 2021, 3:02 PM
Where i can find the 'dr' 'cn' and 'cmd'?
Deepawali MhaisagarPosted May 15, 2021, 7:36 AM
Can you please remove the error from code which I provide you..I am in a very bad situation.. please please please please please please help me ??????????.
Suman KhanPosted May 7, 2021, 3:24 AM
Error 2 The name 'dr' and 'cn' does not exist in the current context ..... please help... previous 2 errors are solved but now these two are showing
Suman KhanPosted May 7, 2021, 3:10 AM
(@ "Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Database.mdf;Integrated Security=True;User Instance=True"); There is errror in this line.... error are following: Error 12 ) expected c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 51 RegistrationAndLoginError 14 ; expected c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 246 RegistrationAndLogin Error 11 Invalid expression term '' c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 49 RegistrationAndLogin Error 13 Invalid expression term ')' c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 246 RegistrationAndLogin Error 1 Keyword, identifier, or string expected after verbatim specifier: @ c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 49 RegistrationAndLogin Error 10 Only assignment, call, increment, decrement, and new object expressions can be used as a statement c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 51 RegistrationAndLogin Error 2 Unrecognized escape sequence c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 66 RegistrationAndLogin Error 3 Unrecognized escape sequence c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 96 RegistrationAndLogin Error 4 Unrecognized escape sequence c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 103 RegistrationAndLogin Error 5 Unrecognized escape sequence c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 109 RegistrationAndLogin Error 6 Unrecognized escape sequence c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 138 RegistrationAndLogin Error 7 Unrecognized escape sequence c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 147 RegistrationAndLogin Error 8 Unrecognized escape sequence c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 168 RegistrationAndLogin Error 9 Unrecognized escape sequence c:\users\suman\documents\visual studio 2010\Projects\RegistrationAndLogin\RegistrationAndLogin\Registrationcs.cs 22 189 RegistrationAndLogin
Suman KhanPosted May 7, 2021, 3:07 AM
Please tell me solution of this error
Suman KhanPosted May 7, 2021, 3:06 AM
The name 'cn' does not exist in the current context...
Albin AlbinPosted May 3, 2021, 7:45 PM
Everything works as intended but for some reason the password doesn't show as *. Any idea why?
Colin ChinPosted May 2, 2021, 3:01 AM
Where does "dr" come from?
ShortBeachGriffy ShortBeachGriffyPosted Apr 14, 2021, 4:01 AM
Sir is this local database how this works? what if I published my app to others do they need to install SQL sir?
Osama SaadPosted Apr 12, 2021, 5:00 AM
Dr stands for what >>dr = cmd.ExecuteReader();
ShortBeachGriffy ShortBeachGriffyPosted Jan 26, 2021, 1:14 PM
Had problem with step 18 can someone help me?
Abdulaziz AlfaifiPosted Oct 23, 2020, 5:55 PM
I hope you upload the source code. i have a problem that i cannot solve to make the app work!