0% found this document useful (0 votes)
4 views

Sample code

The document provides a step-by-step guide to create a Login and Registration form using C# Windows Forms with a database. It includes instructions on setting up the project in Visual Studio, creating forms, adding a database, and implementing the necessary code for user registration and login functionalities. Additionally, it contains code snippets for handling user input and database interactions.

Uploaded by

Naol Bekele
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Sample code

The document provides a step-by-step guide to create a Login and Registration form using C# Windows Forms with a database. It includes instructions on setting up the project in Visual Studio, creating forms, adding a database, and implementing the necessary code for user registration and login functionalities. Additionally, it contains code snippets for handling user input and database interactions.

Uploaded by

Naol Bekele
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

Please test the following code segement

Step 1

Open your visual studio, here I will use Visual Studio.

Step 2

The clock on file menu on top of the visual studio, hover mouse on new, and click
on Project.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

Step 3

Search for Windows Form App and click on next.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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.
Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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”.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Databaseq

CREATE TABLE [dbo].[LoginTable]


(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[username] NVARCHAR(50) NULL,
[password] NVARCHAR(50) NULL
)
SQL
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.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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();
}
C#
Step 12
Go to Server Explorer, right-click on the database, then click on Modify
Connection.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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();
}
C#
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);
}
}
C#
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.

Create Login(Sign In) And Registration (Sign Up) Form In C# Windows Form With
Database

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();
}
C#
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();
}
C#
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);
}
}
C#
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());
}
C#
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);
}
}

}
}
C#
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();
}
}
}
C#
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();
}
}
}
C#
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());
}
}
}

You might also like