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.
Многие приложения требуют авторизации для полноценного использования. Сегодня мы напишем простую форму авторизации Windows-приложений на языке C#.
Шаг 1. Создание базы
Первым делом создадим новую базу данных test
для хранения тестовой информации. Добавьте таблицу user
со следующими полями:
id
(INT) c атрибутомAUTO_INCREMENT
;name
(VARCHAR(100));title
(VARCHAR(100));address
(VARCHAR(100)).
user
в базе данных test
Шаг 2. Создание проекта
Создайте проект для нового приложения. В Visual Studio для этого нужно зайти в меню File
> New
> Project
.
После этого появится окно New Project:
В поле Name
нужно вписать название вашего проекта, в поле Location
– указать нужную директорию, в Solution name
– ввести название решения. Заполнили данные – нажимаем OK
.
Шаг 3. Создание интерфейса
Создайте представление будущей формы авторизации, как показано на рисунке ниже. Добавьте два поля (username
и password
) и кнопку для входа.
Шаг 4. Настройка соединения с базой
Создайте класс connection
для настройки соединения с базой. Пример реализации представлен в листинге ниже:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data;namespace Connection_DB
{
class connection
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
static string host = "localhost";
static string database = "test";
static string userDB = "ecco";
static string password = "password";
public static string strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
public bool Open()
{
try
{
strProvider = "server=" + host + ";Database=" + database + ";User ID=" + userDB + ";Password=" + password;
conn = new MySqlConnection(strProvider);
conn.Open();
return true;
}
catch (Exception er)
{
MessageBox.Show("Connection Error ! " + er.Message, "Information");
}
return false;
} public void Close()
{
conn.Close();
conn.Dispose();
} public DataSet ExecuteDataSet(string sql)
{
try
{
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
da.Fill(ds, "result");
return ds;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
} public MySqlDataReader ExecuteReader(string sql)
{
try
{
MySqlDataReader reader;
MySqlCommand cmd = new MySqlCommand(sql, conn);
reader = cmd.ExecuteReader();
return reader;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
} public int ExecuteNonQuery(string sql)
{
try
{
int affected;
MySqlTransaction mytransaction = conn.BeginTransaction();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
affected = cmd.ExecuteNonQuery();
mytransaction.Commit();
return affected;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return -1;
}
}
}
Наконец, вернитесь к форме и добавьте следующий код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;namespace Connection_DB
{
public partial class Form1 : Form
{
connection con = new connection();
string id, username, password, firstname, lastname, address;
public Form1()
{
InitializeComponent();
} private void btnLogin_Click(object sender, EventArgs e)
{
try
{ if (txtUsername.Text != "" && txtPassword.Text != "")
{
con.Open();
string query = "select id,username,password,firstname,lastname,address from user WHERE username ='" + txtUsername.Text + "' AND password ='" + txtPassword.Text + "'";
MySqlDataReader row;
row = con.ExecuteReader(query);
if (row.HasRows)
{
while (row.Read())
{
id = row["id"].ToString();
username = row["username"].ToString();
password = row["password"].ToString();
firstname = row["firstname"].ToString();
lastname = row["lastname"].ToString();
address = row["address"].ToString();
} MessageBox.Show("Data found your name is " + firstname + " " + lastname + " " + " and your address at " + address);
}
else
{
MessageBox.Show("Data not found", "Information");
}
}
else
{
MessageBox.Show("Username or Password is empty", "Information");
}
}
catch
{
MessageBox.Show("Connection Error", "Information");
}
}
}
}
Результат
Нажмите F5
, чтобы запустить программу. Если соединение с базой данных успешно установится, вы увидите только что созданную форму.
Исходный код этой простой формы авторизации вы найдете на Github.
***
У нас есть много полезных материалов по C# для начинающих:
- Лучшие актуальные шпаргалки по C# на все случаи жизни
- Видеокурс по C# с нуля: от основ до полноценного приложения
- Самый понятный видеокурс по C# для новичков
Источники
- https://www.c-sharpcorner.com/article/simple-login-form-c-sharp-with-database-mysql/