rBuilding a Login Form Application with C# .NET and MySQL Database (2024)

rBuilding a Login Form Application with C#.NET and MySQL Database (2)

In this tutorial, we’ll walk through the process of creating a login form application using C# .NET and MySQL database. We’ll utilize XAMPP server for our backend setup. By the end, you’ll have a fully functional application with three main windows: Login Page, Register Page, and Profile Page.

Let’s dive in step by step:

Start by creating a new C# project with .NET framework. Add three form windows to your project: LoginForm, RegisterForm, and ProfileForm.

For the Login Page, add textboxes for username and password, along with login and register buttons. For the Register Page, include textboxes for first name, last name, username, occupation, and password. Additionally, add buttons for profile picture upload, registration, and navigation to the login page. Finally, design the Profile Page with elements to display profile information and a logout button.

Here are Ui designs

rBuilding a Login Form Application with C#.NET and MySQL Database (3)
rBuilding a Login Form Application with C#.NET and MySQL Database (4)
rBuilding a Login Form Application with C#.NET and MySQL Database (5)

Install the MySqlConnector package using NuGet Package Manager and import MySqlConnector namespace into your project.

Using XAMPP and phpMyAdmin, create a new database named csharploginform and a table named users. Add columns for ID (auto-incrementing), first name, last name, username, occupation, password, and profile picture.

CREATE TABLE IF NOT EXISTS userdetails (
ID INT AUTO_INCREMENT PRIMARY KEY,
FirstName VARCHAR(255) NOT NULL,
Username VARCHAR(255) UNIQUE NOT NULL,
Occupation VARCHAR(255),
Password VARCHAR(255) NOT NULL,
ProfileImage LONGBLOB
);

In the LoginForm.cs file, implement the code to handle user login authentication. This includes connecting to the MySQL database, executing a SELECT query to verify the credentials, and navigating to the Profile Page upon successful login.

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 LoginForm_CSharp.Views;
using MySqlConnector;

namespace LoginForm_CSharp
{
public partial class LoginForm : Form
{
MySqlConnection connection = new MySqlConnection("server=localhost;database=csharploginform;port=3306;username=root;password=");
MySqlCommand command;
MySqlDataReader dr;
public LoginForm()
{
InitializeComponent();
}

private void LoginButton_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(LogUsernameText.Text) || string.IsNullOrEmpty(LogPasswordText.Text))
{
MessageBox.Show("Please enter username and password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}

connection.Open();
string selectQuery = "SELECT * FROM users WHERE Username = @Username AND Password = @Password";
command = new MySqlCommand(selectQuery, connection);
command.Parameters.AddWithValue("@Username", LogUsernameText.Text);
command.Parameters.AddWithValue("@Password", LogPasswordText.Text);
dr = command.ExecuteReader();

if (dr.Read())
{
MessageBox.Show("Login Successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
string LoggedUserName = LogUsernameText.Text;
DashboardForm dashboardForm = new DashboardForm(LoggedUserName);
dashboardForm.Show();
}
else
{
MessageBox.Show("Invalid username or password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}

}

private void GoToRegisterButton_Click(object sender, EventArgs e)
{
this.Hide();
RegisterForm registerForm = new RegisterForm();
registerForm.Show();
}
}
}

In the RegisterForm.cs file, write the code to handle user registration. This involves checking for empty fields, querying the database to ensure username uniqueness, inserting user data into the database, and navigating to the Profile Page upon successful registration.

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 LoginForm_CSharp.Views;
using MySqlConnector;

namespace LoginForm_CSharp
{
public partial class RegisterForm : Form
{
MySqlConnection connection = new MySqlConnection("server=localhost;database=csharploginform;port=3306;username=root;password=");
public RegisterForm()
{
InitializeComponent();
}

private void GotoToLoginButton_Click(object sender, EventArgs e)
{
this.Hide();
LoginForm loginForm = new LoginForm();
loginForm.Show();
}

private void RegisterButton_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(RegFirtsNameText.Text) || string.IsNullOrEmpty(RegLastNameText.Text) || string.IsNullOrEmpty(RegUsernameText.Text) || string.IsNullOrEmpty(RegOccuText.Text) || string.IsNullOrEmpty(RegPasswordText.Text))
{
MessageBox.Show("Please Fill The All Information");
return;
}
connection.Open();
MySqlCommand mySqlCommand1 = new MySqlCommand("SELECT * FROM users WHERE Username = @Username", connection);
mySqlCommand1.Parameters.AddWithValue("@Username", RegUsernameText.Text);
bool userExists = false;

using (var dr1 = mySqlCommand1.ExecuteReader())
if (userExists = dr1.HasRows) MessageBox.Show("Username Allready Exist");

if (!userExists)
{
string iquery = "INSERT INTO csharploginform.users(`ID`, `FirstName`, `LastName`, `Username`, `Occupation`, `Password`, `ProfilePicture`) VALUES(NULL,@FirstName, @LastName,@Username, @Occupation, @Password, @ProfilePicture)";
MySqlCommand commandDatabase = new MySqlCommand(iquery, connection);
commandDatabase.Parameters.AddWithValue("@FirstName", RegFirtsNameText.Text);
commandDatabase.Parameters.AddWithValue("@LastName", RegLastNameText.Text);
commandDatabase.Parameters.AddWithValue("@Username", RegUsernameText.Text);
commandDatabase.Parameters.AddWithValue("@Occupation", RegOccuText.Text);
commandDatabase.Parameters.AddWithValue("@Password", RegPasswordText.Text);

if (RegProPicButton.Image != null)
{
byte[] imageData = ImageToByteArray(RegProPicButton.Image);
commandDatabase.Parameters.AddWithValue("@ProfilePicture", imageData);
}
else
{
commandDatabase.Parameters.AddWithValue("@ProfilePicture", DBNull.Value);
}

commandDatabase.CommandTimeout = 60;
commandDatabase.ExecuteNonQuery();
MessageBox.Show("Account Created Successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
string LoggedUserName = RegUsernameText.Text;
DashboardForm dashboardForm = new DashboardForm(LoggedUserName);
dashboardForm.Show(); ;
}
}
catch(Exception ex)
{
MessageBox.Show("An Error" + ex.Message, "Error");
}
finally
{
connection.Close();
}
}

private void RegProPicButton_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Image Files|*jpg;*jpeg;*png";
fileDialog.Title = "Select an Image File";

if (fileDialog.ShowDialog() == DialogResult.OK)
{
RegProPicButton.Image = new Bitmap(fileDialog.FileName);
}
}

private byte[] ImageToByteArray(Image image)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(image, typeof(byte[]));
}
}
}

In the DashboardForm.cs (Profile Page) file, develop the code to display user profile information fetched from the database. This includes querying the database based on the logged-in user's username and populating the form fields with the retrieved data.

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LoginForm_CSharp.Views
{
public partial class DashboardForm : Form
{
private readonly string username;
private readonly MySqlConnection connection;
public DashboardForm(string username)
{
InitializeComponent();
this.username = username;
connection = new MySqlConnection("server=localhost;database=csharploginform;port=3306;username=root;password=");
DisplayProfile();
}

private void DisplayProfile()
{
try
{
connection.Open();
string query = "SELECT * FROM users WHERE Username = @Username";
MySqlCommand command = new MySqlCommand(query, connection);
command.Parameters.AddWithValue("@Username", username);

using (MySqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
DFirstName.Text = reader["FirstName"].ToString();
DLastName.Text = reader["LastName"].ToString();
DUserName.Text = reader["Username"].ToString();
DOccupation.Text = reader["Occupation"].ToString();

if (reader["ProfilePicture"] != DBNull.Value)
{
byte[] img = (byte[])reader["ProfilePicture"];
using (MemoryStream ms = new MemoryStream(img))
{
ProfilePic.Image = Image.FromStream(ms);
}
}
else
{
MessageBox.Show("No Profile Picture Found");
this.Close();
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
this.Close();
}

}

private Image ResizeImage(Image image, int width, int height)
{
Bitmap resizedImage = new Bitmap(width, height);
using (Graphics graphics = Graphics.FromImage(resizedImage))
{
graphics.DrawImage(image, 0, 0, width, height);
}
return resizedImage;
}

private void LogoutButton_Click(object sender, EventArgs e)
{
this.Hide();
LoginForm loginForm = new LoginForm();
loginForm.Show();
}
}
}

Once the development is complete, test your application to ensure everything works as expected. Verify user login, registration, and profile display functionalities.

That’s it! You’ve successfully built a login form application with C# .NET and MySQL database. For the full project code, check out my GitHub repository here.

Check Out this Repo

Dizzpy | Happy coding! 🖥️🥰

rBuilding a Login Form Application with C# .NET and MySQL Database (2024)

FAQs

How to create a user login form with a C# and SQL Server database? ›

Introduction
  1. Note. ...
  2. Open Visual Studio and create a new Windows Forms project.
  3. Make a simple form having the 2 text fields username and password and a login button.
  4. Now go to the menu bar, select the view option, and there you can see “Server Explorer”. ...
  5. Now add your connection. ...
  6. It'll ask for permission, and click Yes.
Sep 24, 2023

How to connect MySQL database in C# Windows Form Application? ›

  1. Open connection to the database.
  2. Create a MySQL command.
  3. Assign a connection and a query to the command. ...
  4. Create a MySqlDataReader object to read the selected records/data.
  5. Execute the command.
  6. Read the records and display them or store them in a list.
  7. Close the data reader.
  8. Close the connection.

How to make a login form in C#? ›

How To Create Login Form In Windows Application Using C#
  1. First create the table and insert user login credentials. Query for creating the table. CREATE TABLE [dbo].[UserLogins]( ...
  2. Create a Windows form application, using label, textbox and button from Toolbox .
  3. Step 3 - on click Login button it will go in . cs file.
Dec 29, 2017

How to create login form in Visual Studio and connect with MySQL? ›

Let's dive in step by step:
  1. Step 1: Creating a Windows Form Application. ...
  2. Step 2: Designing UI for Our Forms. ...
  3. Step 3: Adding Required Packages. ...
  4. Step 4: Preparing Our Database. ...
  5. Step 5: Coding Our Login Page. ...
  6. Step 6: Coding the Register Page. ...
  7. Step 7: Creating the Profile Page. ...
  8. Step 8: Testing Your Application.
Apr 5, 2024

How do I create a SQL database login? ›

Create a login using SSMS for SQL Server
  1. In Object Explorer, expand the folder of the server instance in which you want to create the new login.
  2. Right-click the Security folder, point to New, and select Login....
  3. In the Login - New dialog box, on the General page, enter the name of a user in the Login name box.
Aug 1, 2023

How to connect a form to a database in C#? ›

Follow the steps below for an easy C# SQL Server Database connection:
  1. Step 1: Install the Entity Framework NuGet Package.
  2. Step 2: Define your Data Model.
  3. Step 3: Create DbContext Class.
  4. Step 4: Configure Connection String.
  5. Step 5: Initialize Database.
  6. Step 6: Use DbContext in Your Code.
Feb 17, 2022

How to connect MySQL database to application? ›

Open MySQL Workbench. Click the + button next to MySQL connections. In the pop-up window, type in what you'd like to call the connection in Connection Name. Then type in the Hostname, Port, Username, and Password (if there is one) for the database you want to connect to.

How to connect form to MySQL? ›

For this you need to follow the following steps:
  1. Step 1: Filter your HTML form requirements for your contact us web page. ...
  2. Step 2: Create a database and a table in MySQL. ...
  3. Step 3: Create HTML form for connecting to database. ...
  4. Step 4: Create a PHP page to save data from HTML form to your MySQL database. ...
  5. Step 5: All done!

How do I create a login form? ›

Steps to Create an HTML Login Form
  1. Set up the HTML Document.
  2. Create the Form Element.
  3. Add Input Fields.
  4. Include a Submit Button:
  5. Optional: Add Additional Features:
  6. Close the Form and Document:
Jun 3, 2024

How to create a form in C# in Windows? ›

Visual Studio opens your new project.
  1. Open Visual Studio.
  2. On the start window, select Create a new project.
  3. In Create a new project, select the Windows Forms App (.NET Framework) template for C#. ...
  4. In the Configure your new project window, in Project name, enter HelloWorld, and select Create.
Mar 28, 2024

How to create log file in C# web application? ›

Each file is written by a separate logger, so you need to use both inside of your code: ILog Log = LogManager. GetLogger(typeof(LogTest)); ILog ErrorLog = LogManager. GetLogger("error"); Log.Info("Debug message"); ErrorLog.

How to create a login page in ASP.NET using C# with MySQL database? ›

Introduction
  1. Create a database in MySQL with the name “test” and create a table with the name “user”, as shown below.
  2. Create a new application project. ...
  3. Then, the window New Project will appear.
  4. Write down the name of the project that will be created on a field Name. ...
  5. Create a new Windows form like below.
Aug 23, 2023

Can you connect MySQL to Visual Studio? ›

Visual Studio does not include support for MySQL by default. To add MySQL support to Visual Studio, you must install the following components: MySQL for Visual Studio: This component adds MySQL support to Visual Studio's visual database tools, such as Server Explorer.

How to create database in login form? ›

Database and Table Creation
  1. Access the phpMyAdmin on the browser using localhost/phpmyadmin/ and create a table in the database. Here we will create a database and table using GUI based phpMyAdmin rather than queries execution.
  2. Click on New and enter the database name and then click on Create button.

How do I create a login for an existing user in SQL Server? ›

Creating a SQL Server login for an existing domain user in SSMS
  1. Step 1: Connect to Your SQL Server Instance. ...
  2. Step 2: Create a New Login. ...
  3. Step 3: Specify Login Name. ...
  4. Step 4: Configure Server Roles. ...
  5. Step 5: Set Default Database (Optional) ...
  6. Step 6: Finalize and Create the Login. ...
  7. Step 7: Verify the Login (Optional)
Mar 2, 2024

How to create user with SQL Server authentication? ›

How to create a SQL server authentication login ID
  1. Run Microsoft SQL Server Management Studio.
  2. Expand the Security item in Object Explorer and right-click Logins and choose New Login….
  3. Enter an account name in the Login name field and choose SQL Server authentication.
Oct 20, 2015

How to create a registration form using asp net C# with SQL database? ›

ADD ENTITY DATA MODEL.
  1. Right click Models Folder-> Add-> Class-> Visual C#-> Data-> ADO.NET Entity data Model-> Entry Name-> ADD.
  2. Entity Data Model Wizard dialog.
  3. Select EF Designer from Database-> Next->New Connection.
  4. Enter your server name-> Choose your authentication, I am using SQL Server authentication.
May 13, 2024

References

Top Articles
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 5625

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.