Csharp Tutorial Login Register Application - Gudio Tutorial

    Social Items


Login Register Application

Hello blogger, wherever you are. Meet again with me in Gudio Blog. Maybe for those of you who have just visited this blog for the first time, you don't know that Gudio Blog is a blog that discusses web, desktop or mobile programming, tips and tricks about blogger, android and others related to technology.

In this article, according to the title, this time I will discuss the Csharp Tutorial which is about Creating an Application Login Register with Csharp (C #). For those of you who still don't understand the Csharp Programming Language, you can read my article below, Csharp For Beginners (Introduction), in my article the basics of Csharp programming are discussed.

In making this application, we will use the MySQL database for user data storage. And we need the MySQL Connector to connect Visual Studio with MySQL. For the way, you can read my article which is Make a Connection From VB.Net to MySQL, even though the article is about Visual Basic, but for how to Add Reference it is the same as Visual Basic with Csharp.

Alright, I won't be lingering for a long time and I'm sure you can't wait to go directly to the tutorial, okay let's start.


Creating a Database

Before we start to Visual Studio, we will create a database first in MySQL. Do you already know how to create a database in MySQL? If not, here's how to make it:

  1. Open your browser (it can be Mozilla, Chrome or anything else you have) and enter it in the address bar: localhost / phpmyadmin. Then you will be directed to the phpMyAdmin page.
  2. Please create a database by selecting "Create New Database". Enter the database name, in this tutorial I will create a database with the name "dbloginreg".
  3. If so, continue by creating a table in the database. In this tutorial I created a table with the name "tblogreg".
  4. And the code below is the name of the column and the value in the tblogreg table.

CREATE TABLE `dbLoginReg`.`tblogreg` ( `no` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(50) NOT NULL , `address` VARCHAR(100) NOT NULL , `username` VARCHAR(50) NOT NULL , `password` VARCHAR(100) NOT NULL , `gender` VARCHAR(15) NOT NULL , `job` VARCHAR(20) NOT NULL , `secureQuestion` VARCHAR(50) NOT NULL , `answer` VARCHAR(50) NOT NULL , PRIMARY KEY (`no`)) ENGINE = InnoDB;

after we create the database, now we will make the application design.



Application Design

In this login register application, we will create four types of forms, namely:

  1. Form To Login
  2. Form To Register
  3. Main Form
  4. Form To Reset Password

Login Form : Component

This form is used to log in for users who already have an account. We will make a design for this form. Below are the components used for this form, you can use your own creation to design this login form.
Component Name of Object Total Function
Group Box groupBox1
groupBox2
2 -
-
Picture Box pictureBox1
pictureBox2
pictureBox3
3 pictureBox1 for logo application
pictureBox2 for username icon picture
pictureBox3 for password icon picture
Label lblUsername
lblPass
lblRegister
lblForgotPass
4 lblUsername for the label in the username column
lblPass for the label in the password column
lblRegister for users who don't have an account
lblForgotPass for users who forget their account password
Text Box txtUsername
txtPass
2 txtUsername to hold user username data
txtPassword to hold password data from users
Button btnSignIn 1 btnSignIn to log in to the main menu if the data inputting the user is correct
Login Form : Form Design

Below is the design form that I made. As I said, please make a design according to what you like or you can use the design like I made.

Login Form Design


Register Form : Component
This Registration Form will be used for new users to register and to be able to log in to the main menu. Below are the components used to design the register form
Component Name of Object Total Function
Group Box groupBox1
groupBox2
2 -
-
Picture Box pictureBox1 1 pictureBox1 to display the logo
Label lblName
lblUsername
lblPassReg
lblConfirm
lblAddress
lblGender
lblJob
lblQuestion
lblAnswer
lblBackToLogin
9 blName is used as a column name label
lblUsername is used as a label for the user's username
lblPassReg is used as a label for the password column
lblConfirm is used as a label for the password confirmation column
lblAddress is used as the user's address column label
lblGender is used as a label of the gender combo box of the user
lblJob is used as a label from the job combo box
lblQuestion is used as a label from the security question combo box
lblAnswer is used as a label for the user's security answer
lblBackToLogin is used to return to the login form menu
TextBox txtName
txtUsername
txtPassReg
txtConfirmPass
txtAddress
txtAnswer
6 txtName is used to hold name data from the user
txtUsername is used to hold user username data
txtPassReg is used to hold password data from users
txtConfirmPass is used to hold password confirmation data from users
txtAddress is used to hold address data from users
txtAnswer is used to hold answers to security questions
ComboBox cmbGender
cmbJob
cmbQuestion
3 cmbGender is used to accommodate the user's gender choices
cmbJob is used to accommodate choices from work
cmbQuestion is used to accommodate a choice of security questions
Button btnRegister 1 btnRegister is used to store data entered by the user into the database

Register Form : Form Design
Below is the design of the form to register please adjust it to your wishes

Form Register Design
.


Main Form : Form Design
On this main form I did not do many things, because the application I made was more about the login and register functions than the main menu

Main Form


Form Reset Password : Component
Component Total Name of Object Function
Group Box 4 groupBox1
groupBox2
groupBox3
groupBox4
-
-
-
-
Picture Box 1 pictureBox1 to display the logo
Label 7 lblInputUsername
lblBackToLogin
lblQuestion
lblSecurityQuestion
lblAnswer
lblNewPassword
lblConfirm
lblUsername is used for the username column
lblBackToLogin is used to return to the login form
lblQuestion is used for the security question column
lblSecurityQuestion is used to display security questions from users
lblAnswer is used for the security question answer column
lblNewPassword is used for the new password column
lblConfirm is used for the password confirmation column
TextBox 4 txtInputUsername
txtAnswer
txtNewPassword
txtConfirmPass
txtInputUsername is used to input the username of the user
txtAnswer is used to hold answers to user security questions
txtNewPassword is used to hold new passwords from users
txtConfirmPass is used to accommodate password confirmation from users
Button 3 btnCheckUsername
btnCheckMyAnswer
btnUpdatePass
btnCheckUsername is used to check whether the username entered by the user is registered in the database or not
btnCheckMyAnswer is used to check whether the user's security answer data matches the database
btnUpdatePass is used to update password data based on the username


Form Reset Password : Form Design
Below is a design example that I made, you can follow according to the example of my design or design according to what you want.

Forgot Password Form Design




Coding (Writing Code)

After you finish designing the application, now is the time to code the program.
Make it a habit to type the program code below, don't just copy and paste. The more you make the program code, the more you will understand the program code. And one thing, there are no programmers who just copy and paste the program code. Trust me

Login Form: Import Reference
Double click on the login form so you will be directed to the writing code, then import the following two codes so that you can connect to mysql.

using MySql.Data.MySqlClient;
using System.Data;


Login Form: Declare Variable
then declare the variable to connect to MySQL. Type the code below. For the Mysql connection, you adjust it with the database name, password and user according to what you created. If you create a database name like the one I created and the database that you created there is no password, then follow the code below:

MySqlConnection connection = new MySqlConnection("server=localhost;user id=root;password=;database=dbloginreg;sslMode=none;");
MySqlCommand cmd;
MySqlDataAdapter adapter;
string query;
int maxrow;
DataTable dt;


Login Form: Code For Label Register dan Forgot Password
Double click on the register label, then type the code below:

private void lblRegister_Click(object sender, EventArgs e)
{
   Hide();
   Form2 formReg = new Form2();
   formReg.ShowDialog();
}

private void lblForgotPass_Click(object sender, EventArgs e)
{
    Hide();
    Form4 frmForgot = new Form4();
    frmForgot.ShowDialog();
}

the explanation of the code above is: when the user clicks on the register label then the login form will be hidden and display the register form. The same thing when the user clicks on the forgot password label.

Login Form: Code For Button Sign In
Then, after you have finished making the code above, we will now continue by coding the sign in button. Double-click on the sign in button and type the following code:

private void btnSignIn_Click(object sender, EventArgs e)
        {
            if(txtUsername.Text.Trim() == string.Empty || txtPass.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please Fill All Data","Gudio Tutorial : Bad Data",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }else
            {
                try
                {
                    query = "SELECT * FROM tblogreg WHERE username='" + txtUsername.Text.Trim() + "' AND password='" + txtPass.Text.Trim() + "'";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    dt = new DataTable();
                    adapter.Fill(dt);

                    maxrow = dt.Rows.Count;
                    if(maxrow > 0)
                    {
                        Hide();
                        Form3 mainfrm = new Form3();
                        mainfrm.ShowDialog();
                    }else
                    {
                        MessageBox.Show("I'm Sorry, your account was not found. Please check your username and password or contact your administrator","Gudio Tutorial : Bad Account",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                        txtPass.Clear();
                        txtUsername.Clear();
                        txtUsername.Focus();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(),"Gudio Tutorial : Failed",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
                finally
                {
                    connection.Close();
                    adapter.Dispose();
                }
            }
        }

Explanation of the Code above:
code below to validate input from users. If the column is still empty but the user has clicked on the sign in button a message box will appear.

if(txtUsername.Text.Trim() == string.Empty || txtPass.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please Fill All Data","Gudio Tutorial : Bad Data",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }


and an explanation of the code below:

  1. first we create a query for the command that the system will implement for data manipulation in the database.
  2. then the connection will be opened.
  3. queries that have been made will be accommodated in the command. Because for execution everything is on this command

query = "SELECT * FROM tblogreg WHERE username='" + txtUsername.Text.Trim() + "' AND password='" + txtPass.Text.Trim() + "'";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    dt = new DataTable();
                    adapter.Fill(dt);

Login Form: Full Code

namespace Login_Register
{
    
    public partial class Form1 : Form
    {
        MySqlConnection connection = new MySqlConnection("server=localhost;user id=root;password=;database=dbloginreg;sslMode=none;");
        MySqlCommand cmd;
        MySqlDataAdapter adapter;
        string query;
        int maxrow;
        DataTable dt;
        public Form1()
        {
            InitializeComponent();
        }

        private void lblRegister_Click(object sender, EventArgs e)
        {
            Hide();
            Form2 formReg = new Form2();
            formReg.ShowDialog();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void btnSignIn_Click(object sender, EventArgs e)
        {
            if(txtUsername.Text.Trim() == string.Empty || txtPass.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please Fill All Data","Gudio Tutorial : Bad Data",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }else
            {
                try
                {
                    query = "SELECT * FROM tblogreg WHERE username='" + txtUsername.Text.Trim() + "' AND password='" + txtPass.Text.Trim() + "'";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    dt = new DataTable();
                    adapter.Fill(dt);

                    maxrow = dt.Rows.Count;
                    if(maxrow > 0)
                    {
                        Hide();
                        Form3 mainfrm = new Form3();
                        mainfrm.ShowDialog();
                    }else
                    {
                        MessageBox.Show("I'm Sorry, your account was not found. Please check your username and password or contact your administrator","Gudio Tutorial : Bad Account",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                        txtPass.Clear();
                        txtUsername.Clear();
                        txtUsername.Focus();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(),"Gudio Tutorial : Failed",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
                finally
                {
                    connection.Close();
                    adapter.Dispose();
                }
            }
        }

        private void lblForgotPass_Click(object sender, EventArgs e)
        {
            Hide();
            Form4 frmForgot = new Form4();
            frmForgot.ShowDialog();
        }
    }
}



Register Form : Making a Private Void
on the registration form you double click and on the code writing page, you first create a simple function that we will call on form load time. Type the following code:

private void FillGender()
        {
            cmbGender.Items.Add("-Please Select Gender-");
            cmbGender.Items.Add("Man");
            cmbGender.Items.Add("Female");
            cmbGender.SelectedIndex = 0;
        }

        private void FillJob()
        {
            cmbJob.Items.Add("-Please Select Your Job-");
            cmbJob.Items.Add("Programmer");
            cmbJob.Items.Add("Blogger");
            cmbJob.Items.Add("Teacher");
            cmbJob.Items.Add("CEO");
            cmbJob.Items.Add("Please Give Me A Job");
            cmbJob.SelectedIndex = 0;
        }

        private void fillQuestion()
        {
            cmbQuestion.Items.Add("- Select Your Secret Question -");
            cmbQuestion.Items.Add("who is my nickname?");
            cmbQuestion.Items.Add("what's the middle name of my father?");
            cmbQuestion.Items.Add("what's the name of my first school?");
            cmbQuestion.Items.Add("what's my cellphone number?");
            cmbQuestion.Items.Add("what's the name of my pet?");
            cmbQuestion.Items.Add("where did my mother live when she was young?");
            cmbQuestion.SelectedIndex = 0;
        }
 private void EmptyData()
        {
            txtAddress.Clear();
            txtAnswer.Clear();
            txtConfirmPass.Clear();
            txtName.Clear();
            txtPassReg.Clear();
            txtUsername.Clear();
            cmbGender.SelectedIndex = 0;
            cmbJob.SelectedIndex = 0;
            cmbQuestion.SelectedIndex = 0;
            txtName.Focus();
        }

the explanation of the code above is:

  1. FillGender is used to fill the gender combo box in the program.
  2. FillJob is used to load a combobox job when the form loads
  3. FillQuestion is used to fill the combobox question when the form loads. This question will later be used if the user forgets the password

Register Form : Form Load

private void Form2_Load(object sender, EventArgs e)
        {
            FillGender();
            FillJob();
            fillQuestion();
        }

the explanation of the code above is:
in accordance with what was made in the previous code, when the form loads, we only have to call the name to display data on the combobox.

Register Form : Register Button
Double click on the register button and type the following code

 if (txtName.Text.Trim() == string.Empty || txtAddress.Text.Trim() == string.Empty || txtUsername.Text.Trim() == string.Empty
                || txtAnswer.Text.Trim() == string.Empty || cmbGender.SelectedIndex == 0 || cmbJob.SelectedIndex == 0 || cmbQuestion.SelectedIndex == 0
                || txtPassReg.Text.Trim() == string.Empty || txtConfirmPass.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please Fill All Data", "Gudio Tutorial : Bad Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (txtConfirmPass.Text.Trim() != txtPassReg.Text.Trim())
            {
                MessageBox.Show("Your password doesn't match. please check again", "Gudio Tutorial : Bad Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtConfirmPass.Focus();
                return;
            }
            else
            {
                try
                {
                    query = "INSERT INTO tblogreg (no,name,address,username,password,gender,job,secureQuestion,answer) VALUES ('','"+ txtName.Text.Trim()+"','"+txtAddress.Text.Trim()+"','"+txtUsername.Text.Trim()+"','"+txtConfirmPass.Text.Trim()+"','"+cmbGender.SelectedItem.ToString()+"','"+cmbJob.SelectedItem.ToString()+"','"+cmbQuestion.SelectedItem.ToString()+"','"+txtAnswer.Text.Trim()+"')";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    dt = new DataTable();
                    adapter.Fill(dt);

                    maxrow = dt.Rows.Count;
                    if(maxrow >= 0)
                    {
                        MessageBox.Show("congratulations, your data has been saved successfully. Please login using your new account","Gudio Tutorial : Success",MessageBoxButtons.OK,MessageBoxIcon.Information);
                        EmptyData();
                    }
                }
                catch (Exception ex)
                {
                  MessageBox.Show(ex.ToString(),"Gudio Tutorial : Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return;
                }finally
                {
                    connection.Close();
                    adapter.Dispose();
                }
               
            }



Main Form : Form Load
there is not much I will explain in this section, because in the main form there is not too much program code. Because all I focus on in this tutorial is Login and Register.

private void button1_Click(object sender, EventArgs e)
        {
            Hide();
            Form1 frmLogin = new Form1();
            frmLogin.ShowDialog();
           
        }



Forgot Password : Form Load
there is only one more form that we will create the program code. This is the last form, the forgot password form. Double click on the form then you will be directed to the code writing page. Type the following code on the form load:

private void Form4_Load(object sender, EventArgs e)
        {
            txtAnswer.Enabled = false;
            lblSecureQuestion.BackColor = Color.Gray;
            btnCheckMyAnswer.Enabled = false;

            txtNewPassword.Enabled = false;
            txtConfirmPass.Enabled = false;
            btnUpdatePass.Enabled = false;
        }




the explanation of the code above is when the forgot password form appears, the system will disable the component, the active component is only the textbox to enter the user's username and button to check the username.

Forgot Password : Button Chek Username
The program code below is used to check the username entered by the user, whether the entered username data is in the database or not. If the username is found in the database, the security question will appear.

 if (txtInputUsername.Text.Trim() == string.Empty)
            {
                MessageBox.Show("please input your username first", "Gudio Tutorial : Bad Username", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                try
                {
                    query = "SELECT secureQuestion,answer FROM tblogreg WHERE username='" + txtInputUsername.Text.Trim() + "'";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    dt = new DataTable();
                    adapter.Fill(dt);

                    maxrow = dt.Rows.Count;
                    if (maxrow > 0)
                    {
                        for (int i = 0; i < maxrow; i++)
                        {
                            UsernameTemp = txtInputUsername.Text;
                            Form4 frmForgot = new Form4();
                            frmForgot.Height = 283;

                            txtInputUsername.Clear();
                            txtInputUsername.Enabled = false;
                            btnCheckUsername.Enabled = false;

                            lblSecureQuestion.BackColor = Color.White;
                            txtAnswer.Enabled = true;
                            txtAnswer.Focus();
                            btnCheckMyAnswer.Enabled = true;

                            DataRow dr = dt.Rows[i];
                            lblSecureQuestion.Text = dr["secureQuestion"].ToString();
                            lblAFromDB.Text = dr["answer"].ToString();
                        }
                    }
                    else
                    {
                        MessageBox.Show("I'm Sorry, your username was not found. Please check your username.", "Gudio Tutorial : Bad Account", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtInputUsername.Clear();
                        txtInputUsername.Focus();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("there was a mistake " + ex.ToString() + " .Please contact your administrator", "Gudio Tutorial : Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                finally
                {
                    connection.Close();
                    adapter.Dispose();
                }
            }



Forgot Password : Button Chek Answer
in the code below it is used to check the security answers entered by the user. Double click on the check answer button and type the code below:

 private void btnCheckMyAnswer_Click(object sender, EventArgs e)
        {
            if(txtAnswer.Text.Trim() == string.Empty)
            {
                MessageBox.Show("please enter the answer to your security question","Gudio Tutorial : Bad Answer",MessageBoxButtons.OK,MessageBoxIcon.Error);
                txtAnswer.Focus();
                return;
            }else if(txtAnswer.Text.Trim() != lblAFromDB.Text.Trim())
            {
                MessageBox.Show("it looks like the answer you entered does not match your security question","Gudio Tutorial : Bad Answer",MessageBoxButtons.OK,MessageBoxIcon.Error);
                txtAnswer.Focus();
                return;
            }else if(txtAnswer.Text.Trim() == lblAFromDB.Text.Trim())
            {
                txtAnswer.Enabled = false;
                lblSecureQuestion.Text = "";
                lblSecureQuestion.BackColor = Color.Gray;
                btnCheckMyAnswer.Enabled = false;
                txtAnswer.Clear();

                txtNewPassword.Enabled = true;
                txtConfirmPass.Enabled = true;
                btnUpdatePass.Enabled = true;
                txtNewPassword.Focus();
            }
        }


Forgot Password : Button Update Password
the code below to make changes to the password of the user. Double-click on the update password button and type the code below:

private void btnUpdatePass_Click(object sender, EventArgs e)
        {
            if (txtNewPassword.Text.Trim() == string.Empty || txtConfirmPass.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please Fill All Data","Gudio Tutorial : Bad Data",MessageBoxButtons.OK,MessageBoxIcon.Error);
                txtNewPassword.Focus();
                return;
            }else if(txtNewPassword.Text.Trim() != txtConfirmPass.Text.Trim())
            {
                MessageBox.Show("the password you input does not match your confirmation password","Gudio Tutorial : Bad Password",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }else
            {
                try
                {
                    query = "UPDATE tblogreg set password='" + txtConfirmPass.Text.Trim() + "' WHERE username='" + UsernameTemp + "'";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    result = cmd.ExecuteNonQuery();
                    if (result >0)
                    {
                        MessageBox.Show("The password has been updated and you will be directed to the login form automatically", "Gudio Tutorial : Success",MessageBoxButtons.OK,MessageBoxIcon.Information);
                        btnUpdatePass.Enabled = false;
                        txtConfirmPass.Enabled = false;
                        txtNewPassword.Enabled = false;
                        txtNewPassword.Clear();
                        txtConfirmPass.Clear();

                        Hide();
                        Form1 frmLogin = new Form1();
                        frmLogin.ShowDialog();
                    }
                }   
                catch (Exception ex)
                {
                    MessageBox.Show("There was something wrong " + ex.ToString()+", please contact your administrator","Gudio Tutorial : Something Wrong",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return;
                }
                finally
                {
                    connection.Close();
                    adapter.Dispose();
                }     
            }
        }




Download Application

If you want to download the application in this tutorial, you can click the button below:





Conclusion

And finally we have finished and managed to make a simple application for logging in and registering new users. If there are problems and don't work, you can explain in the comments column.

Hopefully this csharp tutorial Creating an Application Login Register with Csharp (C #) can be useful for all of you. And if it's useful, you can share my article to your social media and don't forget, follow me on social media to get the latest information updates.

See you and click subscribe so you don't miss out on my other interesting articles.

Regards,
Gudio Blog

Csharp Tutorial Login Register Application


Login Register Application

Hello blogger, wherever you are. Meet again with me in Gudio Blog. Maybe for those of you who have just visited this blog for the first time, you don't know that Gudio Blog is a blog that discusses web, desktop or mobile programming, tips and tricks about blogger, android and others related to technology.

In this article, according to the title, this time I will discuss the Csharp Tutorial which is about Creating an Application Login Register with Csharp (C #). For those of you who still don't understand the Csharp Programming Language, you can read my article below, Csharp For Beginners (Introduction), in my article the basics of Csharp programming are discussed.

In making this application, we will use the MySQL database for user data storage. And we need the MySQL Connector to connect Visual Studio with MySQL. For the way, you can read my article which is Make a Connection From VB.Net to MySQL, even though the article is about Visual Basic, but for how to Add Reference it is the same as Visual Basic with Csharp.

Alright, I won't be lingering for a long time and I'm sure you can't wait to go directly to the tutorial, okay let's start.


Creating a Database

Before we start to Visual Studio, we will create a database first in MySQL. Do you already know how to create a database in MySQL? If not, here's how to make it:

  1. Open your browser (it can be Mozilla, Chrome or anything else you have) and enter it in the address bar: localhost / phpmyadmin. Then you will be directed to the phpMyAdmin page.
  2. Please create a database by selecting "Create New Database". Enter the database name, in this tutorial I will create a database with the name "dbloginreg".
  3. If so, continue by creating a table in the database. In this tutorial I created a table with the name "tblogreg".
  4. And the code below is the name of the column and the value in the tblogreg table.

CREATE TABLE `dbLoginReg`.`tblogreg` ( `no` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(50) NOT NULL , `address` VARCHAR(100) NOT NULL , `username` VARCHAR(50) NOT NULL , `password` VARCHAR(100) NOT NULL , `gender` VARCHAR(15) NOT NULL , `job` VARCHAR(20) NOT NULL , `secureQuestion` VARCHAR(50) NOT NULL , `answer` VARCHAR(50) NOT NULL , PRIMARY KEY (`no`)) ENGINE = InnoDB;

after we create the database, now we will make the application design.



Application Design

In this login register application, we will create four types of forms, namely:

  1. Form To Login
  2. Form To Register
  3. Main Form
  4. Form To Reset Password

Login Form : Component

This form is used to log in for users who already have an account. We will make a design for this form. Below are the components used for this form, you can use your own creation to design this login form.
Component Name of Object Total Function
Group Box groupBox1
groupBox2
2 -
-
Picture Box pictureBox1
pictureBox2
pictureBox3
3 pictureBox1 for logo application
pictureBox2 for username icon picture
pictureBox3 for password icon picture
Label lblUsername
lblPass
lblRegister
lblForgotPass
4 lblUsername for the label in the username column
lblPass for the label in the password column
lblRegister for users who don't have an account
lblForgotPass for users who forget their account password
Text Box txtUsername
txtPass
2 txtUsername to hold user username data
txtPassword to hold password data from users
Button btnSignIn 1 btnSignIn to log in to the main menu if the data inputting the user is correct
Login Form : Form Design

Below is the design form that I made. As I said, please make a design according to what you like or you can use the design like I made.

Login Form Design


Register Form : Component
This Registration Form will be used for new users to register and to be able to log in to the main menu. Below are the components used to design the register form
Component Name of Object Total Function
Group Box groupBox1
groupBox2
2 -
-
Picture Box pictureBox1 1 pictureBox1 to display the logo
Label lblName
lblUsername
lblPassReg
lblConfirm
lblAddress
lblGender
lblJob
lblQuestion
lblAnswer
lblBackToLogin
9 blName is used as a column name label
lblUsername is used as a label for the user's username
lblPassReg is used as a label for the password column
lblConfirm is used as a label for the password confirmation column
lblAddress is used as the user's address column label
lblGender is used as a label of the gender combo box of the user
lblJob is used as a label from the job combo box
lblQuestion is used as a label from the security question combo box
lblAnswer is used as a label for the user's security answer
lblBackToLogin is used to return to the login form menu
TextBox txtName
txtUsername
txtPassReg
txtConfirmPass
txtAddress
txtAnswer
6 txtName is used to hold name data from the user
txtUsername is used to hold user username data
txtPassReg is used to hold password data from users
txtConfirmPass is used to hold password confirmation data from users
txtAddress is used to hold address data from users
txtAnswer is used to hold answers to security questions
ComboBox cmbGender
cmbJob
cmbQuestion
3 cmbGender is used to accommodate the user's gender choices
cmbJob is used to accommodate choices from work
cmbQuestion is used to accommodate a choice of security questions
Button btnRegister 1 btnRegister is used to store data entered by the user into the database

Register Form : Form Design
Below is the design of the form to register please adjust it to your wishes

Form Register Design
.


Main Form : Form Design
On this main form I did not do many things, because the application I made was more about the login and register functions than the main menu

Main Form


Form Reset Password : Component
Component Total Name of Object Function
Group Box 4 groupBox1
groupBox2
groupBox3
groupBox4
-
-
-
-
Picture Box 1 pictureBox1 to display the logo
Label 7 lblInputUsername
lblBackToLogin
lblQuestion
lblSecurityQuestion
lblAnswer
lblNewPassword
lblConfirm
lblUsername is used for the username column
lblBackToLogin is used to return to the login form
lblQuestion is used for the security question column
lblSecurityQuestion is used to display security questions from users
lblAnswer is used for the security question answer column
lblNewPassword is used for the new password column
lblConfirm is used for the password confirmation column
TextBox 4 txtInputUsername
txtAnswer
txtNewPassword
txtConfirmPass
txtInputUsername is used to input the username of the user
txtAnswer is used to hold answers to user security questions
txtNewPassword is used to hold new passwords from users
txtConfirmPass is used to accommodate password confirmation from users
Button 3 btnCheckUsername
btnCheckMyAnswer
btnUpdatePass
btnCheckUsername is used to check whether the username entered by the user is registered in the database or not
btnCheckMyAnswer is used to check whether the user's security answer data matches the database
btnUpdatePass is used to update password data based on the username


Form Reset Password : Form Design
Below is a design example that I made, you can follow according to the example of my design or design according to what you want.

Forgot Password Form Design




Coding (Writing Code)

After you finish designing the application, now is the time to code the program.
Make it a habit to type the program code below, don't just copy and paste. The more you make the program code, the more you will understand the program code. And one thing, there are no programmers who just copy and paste the program code. Trust me

Login Form: Import Reference
Double click on the login form so you will be directed to the writing code, then import the following two codes so that you can connect to mysql.

using MySql.Data.MySqlClient;
using System.Data;


Login Form: Declare Variable
then declare the variable to connect to MySQL. Type the code below. For the Mysql connection, you adjust it with the database name, password and user according to what you created. If you create a database name like the one I created and the database that you created there is no password, then follow the code below:

MySqlConnection connection = new MySqlConnection("server=localhost;user id=root;password=;database=dbloginreg;sslMode=none;");
MySqlCommand cmd;
MySqlDataAdapter adapter;
string query;
int maxrow;
DataTable dt;


Login Form: Code For Label Register dan Forgot Password
Double click on the register label, then type the code below:

private void lblRegister_Click(object sender, EventArgs e)
{
   Hide();
   Form2 formReg = new Form2();
   formReg.ShowDialog();
}

private void lblForgotPass_Click(object sender, EventArgs e)
{
    Hide();
    Form4 frmForgot = new Form4();
    frmForgot.ShowDialog();
}

the explanation of the code above is: when the user clicks on the register label then the login form will be hidden and display the register form. The same thing when the user clicks on the forgot password label.

Login Form: Code For Button Sign In
Then, after you have finished making the code above, we will now continue by coding the sign in button. Double-click on the sign in button and type the following code:

private void btnSignIn_Click(object sender, EventArgs e)
        {
            if(txtUsername.Text.Trim() == string.Empty || txtPass.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please Fill All Data","Gudio Tutorial : Bad Data",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }else
            {
                try
                {
                    query = "SELECT * FROM tblogreg WHERE username='" + txtUsername.Text.Trim() + "' AND password='" + txtPass.Text.Trim() + "'";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    dt = new DataTable();
                    adapter.Fill(dt);

                    maxrow = dt.Rows.Count;
                    if(maxrow > 0)
                    {
                        Hide();
                        Form3 mainfrm = new Form3();
                        mainfrm.ShowDialog();
                    }else
                    {
                        MessageBox.Show("I'm Sorry, your account was not found. Please check your username and password or contact your administrator","Gudio Tutorial : Bad Account",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                        txtPass.Clear();
                        txtUsername.Clear();
                        txtUsername.Focus();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(),"Gudio Tutorial : Failed",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
                finally
                {
                    connection.Close();
                    adapter.Dispose();
                }
            }
        }

Explanation of the Code above:
code below to validate input from users. If the column is still empty but the user has clicked on the sign in button a message box will appear.

if(txtUsername.Text.Trim() == string.Empty || txtPass.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please Fill All Data","Gudio Tutorial : Bad Data",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }


and an explanation of the code below:

  1. first we create a query for the command that the system will implement for data manipulation in the database.
  2. then the connection will be opened.
  3. queries that have been made will be accommodated in the command. Because for execution everything is on this command

query = "SELECT * FROM tblogreg WHERE username='" + txtUsername.Text.Trim() + "' AND password='" + txtPass.Text.Trim() + "'";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    dt = new DataTable();
                    adapter.Fill(dt);

Login Form: Full Code

namespace Login_Register
{
    
    public partial class Form1 : Form
    {
        MySqlConnection connection = new MySqlConnection("server=localhost;user id=root;password=;database=dbloginreg;sslMode=none;");
        MySqlCommand cmd;
        MySqlDataAdapter adapter;
        string query;
        int maxrow;
        DataTable dt;
        public Form1()
        {
            InitializeComponent();
        }

        private void lblRegister_Click(object sender, EventArgs e)
        {
            Hide();
            Form2 formReg = new Form2();
            formReg.ShowDialog();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void btnSignIn_Click(object sender, EventArgs e)
        {
            if(txtUsername.Text.Trim() == string.Empty || txtPass.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please Fill All Data","Gudio Tutorial : Bad Data",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }else
            {
                try
                {
                    query = "SELECT * FROM tblogreg WHERE username='" + txtUsername.Text.Trim() + "' AND password='" + txtPass.Text.Trim() + "'";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    dt = new DataTable();
                    adapter.Fill(dt);

                    maxrow = dt.Rows.Count;
                    if(maxrow > 0)
                    {
                        Hide();
                        Form3 mainfrm = new Form3();
                        mainfrm.ShowDialog();
                    }else
                    {
                        MessageBox.Show("I'm Sorry, your account was not found. Please check your username and password or contact your administrator","Gudio Tutorial : Bad Account",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                        txtPass.Clear();
                        txtUsername.Clear();
                        txtUsername.Focus();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(),"Gudio Tutorial : Failed",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
                finally
                {
                    connection.Close();
                    adapter.Dispose();
                }
            }
        }

        private void lblForgotPass_Click(object sender, EventArgs e)
        {
            Hide();
            Form4 frmForgot = new Form4();
            frmForgot.ShowDialog();
        }
    }
}



Register Form : Making a Private Void
on the registration form you double click and on the code writing page, you first create a simple function that we will call on form load time. Type the following code:

private void FillGender()
        {
            cmbGender.Items.Add("-Please Select Gender-");
            cmbGender.Items.Add("Man");
            cmbGender.Items.Add("Female");
            cmbGender.SelectedIndex = 0;
        }

        private void FillJob()
        {
            cmbJob.Items.Add("-Please Select Your Job-");
            cmbJob.Items.Add("Programmer");
            cmbJob.Items.Add("Blogger");
            cmbJob.Items.Add("Teacher");
            cmbJob.Items.Add("CEO");
            cmbJob.Items.Add("Please Give Me A Job");
            cmbJob.SelectedIndex = 0;
        }

        private void fillQuestion()
        {
            cmbQuestion.Items.Add("- Select Your Secret Question -");
            cmbQuestion.Items.Add("who is my nickname?");
            cmbQuestion.Items.Add("what's the middle name of my father?");
            cmbQuestion.Items.Add("what's the name of my first school?");
            cmbQuestion.Items.Add("what's my cellphone number?");
            cmbQuestion.Items.Add("what's the name of my pet?");
            cmbQuestion.Items.Add("where did my mother live when she was young?");
            cmbQuestion.SelectedIndex = 0;
        }
 private void EmptyData()
        {
            txtAddress.Clear();
            txtAnswer.Clear();
            txtConfirmPass.Clear();
            txtName.Clear();
            txtPassReg.Clear();
            txtUsername.Clear();
            cmbGender.SelectedIndex = 0;
            cmbJob.SelectedIndex = 0;
            cmbQuestion.SelectedIndex = 0;
            txtName.Focus();
        }

the explanation of the code above is:

  1. FillGender is used to fill the gender combo box in the program.
  2. FillJob is used to load a combobox job when the form loads
  3. FillQuestion is used to fill the combobox question when the form loads. This question will later be used if the user forgets the password

Register Form : Form Load

private void Form2_Load(object sender, EventArgs e)
        {
            FillGender();
            FillJob();
            fillQuestion();
        }

the explanation of the code above is:
in accordance with what was made in the previous code, when the form loads, we only have to call the name to display data on the combobox.

Register Form : Register Button
Double click on the register button and type the following code

 if (txtName.Text.Trim() == string.Empty || txtAddress.Text.Trim() == string.Empty || txtUsername.Text.Trim() == string.Empty
                || txtAnswer.Text.Trim() == string.Empty || cmbGender.SelectedIndex == 0 || cmbJob.SelectedIndex == 0 || cmbQuestion.SelectedIndex == 0
                || txtPassReg.Text.Trim() == string.Empty || txtConfirmPass.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please Fill All Data", "Gudio Tutorial : Bad Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (txtConfirmPass.Text.Trim() != txtPassReg.Text.Trim())
            {
                MessageBox.Show("Your password doesn't match. please check again", "Gudio Tutorial : Bad Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtConfirmPass.Focus();
                return;
            }
            else
            {
                try
                {
                    query = "INSERT INTO tblogreg (no,name,address,username,password,gender,job,secureQuestion,answer) VALUES ('','"+ txtName.Text.Trim()+"','"+txtAddress.Text.Trim()+"','"+txtUsername.Text.Trim()+"','"+txtConfirmPass.Text.Trim()+"','"+cmbGender.SelectedItem.ToString()+"','"+cmbJob.SelectedItem.ToString()+"','"+cmbQuestion.SelectedItem.ToString()+"','"+txtAnswer.Text.Trim()+"')";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    dt = new DataTable();
                    adapter.Fill(dt);

                    maxrow = dt.Rows.Count;
                    if(maxrow >= 0)
                    {
                        MessageBox.Show("congratulations, your data has been saved successfully. Please login using your new account","Gudio Tutorial : Success",MessageBoxButtons.OK,MessageBoxIcon.Information);
                        EmptyData();
                    }
                }
                catch (Exception ex)
                {
                  MessageBox.Show(ex.ToString(),"Gudio Tutorial : Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return;
                }finally
                {
                    connection.Close();
                    adapter.Dispose();
                }
               
            }



Main Form : Form Load
there is not much I will explain in this section, because in the main form there is not too much program code. Because all I focus on in this tutorial is Login and Register.

private void button1_Click(object sender, EventArgs e)
        {
            Hide();
            Form1 frmLogin = new Form1();
            frmLogin.ShowDialog();
           
        }



Forgot Password : Form Load
there is only one more form that we will create the program code. This is the last form, the forgot password form. Double click on the form then you will be directed to the code writing page. Type the following code on the form load:

private void Form4_Load(object sender, EventArgs e)
        {
            txtAnswer.Enabled = false;
            lblSecureQuestion.BackColor = Color.Gray;
            btnCheckMyAnswer.Enabled = false;

            txtNewPassword.Enabled = false;
            txtConfirmPass.Enabled = false;
            btnUpdatePass.Enabled = false;
        }




the explanation of the code above is when the forgot password form appears, the system will disable the component, the active component is only the textbox to enter the user's username and button to check the username.

Forgot Password : Button Chek Username
The program code below is used to check the username entered by the user, whether the entered username data is in the database or not. If the username is found in the database, the security question will appear.

 if (txtInputUsername.Text.Trim() == string.Empty)
            {
                MessageBox.Show("please input your username first", "Gudio Tutorial : Bad Username", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                try
                {
                    query = "SELECT secureQuestion,answer FROM tblogreg WHERE username='" + txtInputUsername.Text.Trim() + "'";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = cmd;
                    dt = new DataTable();
                    adapter.Fill(dt);

                    maxrow = dt.Rows.Count;
                    if (maxrow > 0)
                    {
                        for (int i = 0; i < maxrow; i++)
                        {
                            UsernameTemp = txtInputUsername.Text;
                            Form4 frmForgot = new Form4();
                            frmForgot.Height = 283;

                            txtInputUsername.Clear();
                            txtInputUsername.Enabled = false;
                            btnCheckUsername.Enabled = false;

                            lblSecureQuestion.BackColor = Color.White;
                            txtAnswer.Enabled = true;
                            txtAnswer.Focus();
                            btnCheckMyAnswer.Enabled = true;

                            DataRow dr = dt.Rows[i];
                            lblSecureQuestion.Text = dr["secureQuestion"].ToString();
                            lblAFromDB.Text = dr["answer"].ToString();
                        }
                    }
                    else
                    {
                        MessageBox.Show("I'm Sorry, your username was not found. Please check your username.", "Gudio Tutorial : Bad Account", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtInputUsername.Clear();
                        txtInputUsername.Focus();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("there was a mistake " + ex.ToString() + " .Please contact your administrator", "Gudio Tutorial : Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                finally
                {
                    connection.Close();
                    adapter.Dispose();
                }
            }



Forgot Password : Button Chek Answer
in the code below it is used to check the security answers entered by the user. Double click on the check answer button and type the code below:

 private void btnCheckMyAnswer_Click(object sender, EventArgs e)
        {
            if(txtAnswer.Text.Trim() == string.Empty)
            {
                MessageBox.Show("please enter the answer to your security question","Gudio Tutorial : Bad Answer",MessageBoxButtons.OK,MessageBoxIcon.Error);
                txtAnswer.Focus();
                return;
            }else if(txtAnswer.Text.Trim() != lblAFromDB.Text.Trim())
            {
                MessageBox.Show("it looks like the answer you entered does not match your security question","Gudio Tutorial : Bad Answer",MessageBoxButtons.OK,MessageBoxIcon.Error);
                txtAnswer.Focus();
                return;
            }else if(txtAnswer.Text.Trim() == lblAFromDB.Text.Trim())
            {
                txtAnswer.Enabled = false;
                lblSecureQuestion.Text = "";
                lblSecureQuestion.BackColor = Color.Gray;
                btnCheckMyAnswer.Enabled = false;
                txtAnswer.Clear();

                txtNewPassword.Enabled = true;
                txtConfirmPass.Enabled = true;
                btnUpdatePass.Enabled = true;
                txtNewPassword.Focus();
            }
        }


Forgot Password : Button Update Password
the code below to make changes to the password of the user. Double-click on the update password button and type the code below:

private void btnUpdatePass_Click(object sender, EventArgs e)
        {
            if (txtNewPassword.Text.Trim() == string.Empty || txtConfirmPass.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please Fill All Data","Gudio Tutorial : Bad Data",MessageBoxButtons.OK,MessageBoxIcon.Error);
                txtNewPassword.Focus();
                return;
            }else if(txtNewPassword.Text.Trim() != txtConfirmPass.Text.Trim())
            {
                MessageBox.Show("the password you input does not match your confirmation password","Gudio Tutorial : Bad Password",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }else
            {
                try
                {
                    query = "UPDATE tblogreg set password='" + txtConfirmPass.Text.Trim() + "' WHERE username='" + UsernameTemp + "'";
                    connection.Open();
                    cmd = new MySqlCommand();
                    cmd.Connection = connection;
                    cmd.CommandText = query;
                    result = cmd.ExecuteNonQuery();
                    if (result >0)
                    {
                        MessageBox.Show("The password has been updated and you will be directed to the login form automatically", "Gudio Tutorial : Success",MessageBoxButtons.OK,MessageBoxIcon.Information);
                        btnUpdatePass.Enabled = false;
                        txtConfirmPass.Enabled = false;
                        txtNewPassword.Enabled = false;
                        txtNewPassword.Clear();
                        txtConfirmPass.Clear();

                        Hide();
                        Form1 frmLogin = new Form1();
                        frmLogin.ShowDialog();
                    }
                }   
                catch (Exception ex)
                {
                    MessageBox.Show("There was something wrong " + ex.ToString()+", please contact your administrator","Gudio Tutorial : Something Wrong",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return;
                }
                finally
                {
                    connection.Close();
                    adapter.Dispose();
                }     
            }
        }




Download Application

If you want to download the application in this tutorial, you can click the button below:





Conclusion

And finally we have finished and managed to make a simple application for logging in and registering new users. If there are problems and don't work, you can explain in the comments column.

Hopefully this csharp tutorial Creating an Application Login Register with Csharp (C #) can be useful for all of you. And if it's useful, you can share my article to your social media and don't forget, follow me on social media to get the latest information updates.

See you and click subscribe so you don't miss out on my other interesting articles.

Regards,
Gudio Blog
iklan related post
Load comments