Как сделать регистрацию windows forms

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:

  1. Project Name: Name of your project
  2. Location: Location where you want to store your app on your local computer.
  3. Solution Name: This name is displayed in solution explorer in visual studio.
  4. 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

  1. First, we hide the current form which is registration .
  2. 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

  1. 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.
  2. Then we check if the password and confirm password both are the same.
  3. Then we check if any record/user is already registered with that username if not then continue further otherwise show an error message.
  4. 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

  1. Here, first of all, we check if the user enters a value in both fields. If yes, then continue, otherwise, show an error message.
  2. 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.

Many developers in recent years have been using C# to develop their applications. In this tutorial, we’ll go through a simple example of how to create a basic user authentication in C#.

Introduction

C# or C-sharp is an object-oriented programming language developed by Microsoft. C# or C-sharp runs on a framework called the .Net framework.

The language has created many applications like:

  • Web applications
  • Mobile applications
  • Computer games
  • Desktop applications
  • Database applications
  • Virtual reality applications

Prerequisites

To follow this article along it would be helpful to have the following:

  • An editor, in my case, I’ll be using Visual Studio.
  • Some basic C# and SQL knowledge.
  • Knowledge on how to run relational database management in this case, we will use MySQL.
  • Visual Studio knowledge and how to create projects.

Step I: Create a database and table with required columns


   Create database userdata;

DATABASE CREATION

Create table command:


    CREATE TABLE `user_info` ( `id` INT NOT NULL AUTO_INCREMENT , `names` VARCHAR(50) NOT NULL , `username` VARCHAR(20) NOT NULL , `password` VARCHAR(50) NOT NULL , PRIMARY KEY (`id`)) ;

TABLE CREATION

Step II: Create a project

Create a Visual Studio project by clicking on File -> New -> Project and then select Visual C#. From the window, choose Windows Forms App(.Net Framework). Give your application a name. Then click ok. The project will come with default form called Form 1.

Step III: Create a config class to execute MySQL queries

Since C# is object-oriented, we will create a class that will handle the execution of queries that we will use in our program.

From the Solution Explorer window right-click and select add -> New Item -> Class. Name the class Config.cs the click on the button add.

  • Add MySQL.Data Library by right-clicking on solution explorer window, then Manage Nuget packages, then search for MySQL.Data Library and install.

MYSQL LIBRARY

  • Add the following class to help in the execution of MySQL queries.

Config.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
//add this for MessageBox
using System.Windows.Forms;

// add data function classes
using System.Data;

namespace LoginSysten
{
    public class Config
    {
        string ConectionString = "";  // save connection string
        public MySqlConnection connection = null;
        public string server = "127.0.0.1";// MySQL host / ip of the computer
        public string user = "root";// MySQL user
        public string password = "";// MySQL password 
        DataSet ds;
        DataTable dt;
        public string Table = "user_info"; // initialize db table
        public string ConnectionType = "";
        string RecordSource = "";

        DataGridView tempdata;

        public Config()
        {

        }

        // function to connect to the database
        public void Connect(string database_name)
        {
            try
            {

                   ConectionString = "SERVER=" + server + ";" + "DATABASE=" + database_name + ";" + "UID=" + user + ";" + "PASSWORD=" + password + ";";

                connection = new MySqlConnection(ConectionString);
            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message);
            }
        }

        // Function to execute select statements
        public void ExecuteSql(string Sql_command)
        {

            nowquiee(Sql_command);

        }

        // creates connection to MySQL before execution
        public void nowquiee(string sql_comm)
        {
            try
            {
                MySqlConnection cs = new MySqlConnection(ConectionString);
                cs.Open();
                MySqlCommand myc = new MySqlCommand(sql_comm, cs);
                myc.ExecuteNonQuery();
                cs.Close();


            }
            catch (Exception err)
            {

                MessageBox.Show(err.Message);
            }
        }

        // function to execute delete , insert and update
        public void Execute(string Sql_command)
        {
            RecordSource = Sql_command;
            ConnectionType = Table;
            dt = new DataTable(ConnectionType);
            try
            {
                string command = RecordSource.ToUpper();

                //======================if sql contains select==========================================
                MySqlDataAdapter da2 = new MySqlDataAdapter(RecordSource, connection);

                DataSet tempds = new DataSet();
                da2.Fill(tempds, ConnectionType);
                da2.Fill(tempds);

                //======================================================================================


            }
            catch (Exception err) { MessageBox.Show(err.Message); }
        }

        // function to bring selected results based on column name and row index
        public string Results(int ROW, string COLUMN_NAME)
        {
            try
            {
                return dt.Rows[ROW][COLUMN_NAME].ToString();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                return "";

            }
        }

        // function to bring selected results based on column index and row index
        public string Results(int ROW, int COLUMN_NAME)
        {
            try
            {
                return dt.Rows[ROW][COLUMN_NAME].ToString();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                return dt.Rows[ROW][COLUMN_NAME].ToString();

            }
        }

        // Execute select statement
        public void ExecuteSelect(string Sql_command)
        {
            RecordSource = Sql_command;
            ConnectionType = Table;

            dt = new DataTable(ConnectionType);
            try
            {
                string command = RecordSource.ToUpper();
                MySqlDataAdapter da = new MySqlDataAdapter(RecordSource, connection);
                ds = new DataSet();
                da.Fill(ds, ConnectionType);
                da.Fill(dt);
                tempdata = new DataGridView();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }


        }

        // count Number of rows after selecy
        public int Count()
        {
            return dt.Rows.Count;
        }
    }
}
  • Now that we have Config.cs, we can execute any MySQL statement.

Step IV: Create register windows form

In Microsoft Visual Studio, create a new project. Choose project -> Add Windows Form from File submenu in the left corner, give the form a name Register , and click Add.

We have two Windows form classes that is Form1.cs and Register.cs.

Step V: Design login and register interface

Login form

  • Click on Form1.cs in Solution Explorer, and on the form that displays, add three buttons, two textboxes, and two labels.

The first button will be the register button, that launch the Register form. The second button will be the Login button. When the second button is clicked, it will query the database with the input entered. The second button will execute the login MySQL query. The third button will close the application.

The first textbox will allow the username input for login, while the second textbox will enable the password’s input. These two inputs will be passed to the SQL.

The labels will indicate the functionality of the two textboxes.

LOGIN INTERFACE

Register form

  • Click on Register.cs in the Solution Explorer and on the form that displays add two buttons, three textboxes, and three labels.

The first button will be a register button to save data entered, and the second one will be an exit button that will close the Register form.

The first textbox will allow the input of the names for the user. The second textbox will allow input of the user’s username. The third textbox is for entering the password.

The labels will or show the functionality of the three textboxes.

REGISTER INTERFACE

Step VI: Login logic

  • Initialize the Config file in Form1.cs to allow us to access the database with ease.

 // Initialize the connection class
        Config db = new Config();
        public Form1()
        {
            InitializeComponent();
            // pass the database you want to connect to
            db.Connect("userdata");
        }

On click of the register button, add the following code.


 // start register window
            Register register = new Register();
            register.Show();

On click of the login button, add the following code.


  // querry MySQL database for the data passed from textboxes
            db.ExecuteSelect("SELECT * FROM `user_info` where username='" + textBox1.Text+ "' and password ='" + textBox2.Text+"'");

            if (db.Count() == 1)
            {
                MessageBox.Show("Success You will Login as"+db.Results(0, "names"));
            }
            else
            {
                MessageBox.Show("Wrong username and password combination" );
            }

On click of the exit button, add the following code.


  private void button3_Click(object sender, EventArgs e)
        {
            // closes the application
            Environment.Exit(0);
        }

Final Form1.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 LoginSysten
{
    public partial class Form1 : Form
    {

        // Initialize the connection class
        Config db = new Config();
        public Form1()
        {
            InitializeComponent();

            // pass the database you want to connect to
            db.Connect("userdata");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // querry MySQL database for the data passed from textboxes
            db.ExecuteSelect("SELECT * FROM `user_info` where username='" + textBox1.Text+ "' and password ='" + textBox2.Text+"'");

            if (db.Count() == 1)
            {
                MessageBox.Show("Success You will Login as"+db.Results(0, "names"));
            }
            else
            {
                MessageBox.Show("Wrong username and password combination" );
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // start register window
            Register register = new Register();

            register.Show();
        }

        private void button3_Click(object sender, EventArgs e)
        {

            // closes the application
            Environment.Exit(0);
        }
    }
}

Step VII: Register logic

  • Initialize the Config file in Register.cs to allow us to access the database with ease.

  Config db = new Config();
        public Register()
        {
            InitializeComponent();
            // pass the database you want to connect to
            db.Connect("userdata");
        }

On click of the exit button, add the following code.


 private void button3_Click(object sender, EventArgs e)
        {
            // closses the register window
            this.Close();
        }

On click of the register button, add the following code to save the information.


     private void button2_Click(object sender, EventArgs e)
        {
            // saves data in the database
            db.Execute("INSERT INTO `user_info` (`id`, `names`, `username`, `password`) VALUES (NULL, '"+textBox3.Text+"', '"+textBox1.Text+"', '"+textBox2.Text+"');");

            this.Close()
        }

Find the above application in GitHub Login and Register application.

Conclusion

From the example above, we have seen how we can use C# to create a Desktop system with a login functionality. The object-oriented functionality helps in code re-use without doing much coding from scratch.

In this article:

  • We created a database for our application.
  • Created Login and Register Interfaces.
  • Connected our application with the database.
  • Coded logic and functionality.

Happy C-sharp coding ahead!


Peer Review Contributions by: Miller Juma

Submitted by razormist on Thursday, April 12, 2018 — 21:38.

In this tutorial we will create a Simple Registration And Login Application using C#. C# syntax is highly expressive, yet it is also simple and easy to learn. C# is very simplified for the beginners. It is a general-purpose language designed to make all things simpler. It contains several classes that support any C# platforms, like game development. It has a friendly environment for all new developers. So let’s do the coding…

Getting Started

First you will have to download & install the Visual Studio. Visual Studios is an open source development feel free to create any application that you want.

Here’s the link for the Visual Studio https://www.visualstudio.com/.

Here’s the link for the SQLite Browser http://sqlitebrowser.org/.

Setting up SQLite

SQLite is very carefully tested prior to every release and relevant to use in some way. SQLite is very usable in any environments especially in embedded devices. First all you need to do is to install the components of the SQLIte database, by right clicking in the Main project title in the solution explorer then selecting the Manage NuGet Packages.

tut1

Then go to the browse and search sqlite, after that install it and wait until the process is completed.

tut2

Next go to the Updates and update the needed framework to make sqlite work properly.

tut3

Application Design

We will now create the design for the application, first locate the designer file called form1.Designer.cs, this is the default name when you create a new windows form. Rename the form as Login.cs and then write these codes inside your designer file.

  1. namespace Simple_Registration_and_Login_Application

  2. {

  3. partial class Login

  4. {

  5. /// <summary>

  6. /// Required designer variable.

  7. /// </summary>

  8. private System.ComponentModel.IContainer components = null;

  9. /// <summary>

  10. /// Clean up any resources being used.

  11. /// </summary>

  12. /// <param name=»disposing»>true if managed resources should be disposed; otherwise, false.</param>

  13. protected override void Dispose(bool disposing)

  14. {

  15. if (disposing && (components != null))

  16. {

  17.                 components.Dispose();

  18. }

  19. base.Dispose(disposing);

  20. }

  21. #region Windows Form Designer generated code

  22. /// <summary>

  23. /// Required method for Designer support — do not modify

  24. /// the contents of this method with the code editor.

  25. /// </summary>

  26. private void InitializeComponent()

  27. {

  28. this.label1 = new System.Windows.Forms.Label();

  29. this.txt_username = new System.Windows.Forms.TextBox();

  30. this.label2 = new System.Windows.Forms.Label();

  31. this.txt_password = new System.Windows.Forms.TextBox();

  32. this.btn_login = new System.Windows.Forms.Button();

  33. this.button1 = new System.Windows.Forms.Button();

  34. this.SuspendLayout();

  35. //

  36. // label1

  37. //

  38. this.label1.AutoSize = true;

  39. this.label1.Font = new System.Drawing.Font(«Arial», 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  40. this.label1.Location = new System.Drawing.Point(128, 54);

  41. this.label1.Name = «label1»;

  42. this.label1.Size = new System.Drawing.Size(202, 45);

  43. this.label1.TabIndex = 0;

  44. this.label1.Text = «Username»;

  45. //

  46. // txt_username

  47. //

  48. this.txt_username.Font = new System.Drawing.Font(«Arial Narrow», 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  49. this.txt_username.Location = new System.Drawing.Point(138, 123);

  50. this.txt_username.Name = «txt_username»;

  51. this.txt_username.Size = new System.Drawing.Size(439, 53);

  52. this.txt_username.TabIndex = 1;

  53. //

  54. // label2

  55. //

  56. this.label2.AutoSize = true;

  57. this.label2.Font = new System.Drawing.Font(«Arial», 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  58. this.label2.Location = new System.Drawing.Point(128, 237);

  59. this.label2.Name = «label2»;

  60. this.label2.Size = new System.Drawing.Size(193, 45);

  61. this.label2.TabIndex = 2;

  62. this.label2.Text = «Password»;

  63. //

  64. // txt_password

  65. //

  66. this.txt_password.Font = new System.Drawing.Font(«Arial», 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  67. this.txt_password.Location = new System.Drawing.Point(138, 304);

  68. this.txt_password.Name = «txt_password»;

  69. this.txt_password.Size = new System.Drawing.Size(439, 53);

  70. this.txt_password.TabIndex = 3;

  71. this.txt_password.UseSystemPasswordChar = true;

  72. //

  73. // btn_login

  74. //

  75. this.btn_login.Font = new System.Drawing.Font(«Arial», 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  76. this.btn_login.Location = new System.Drawing.Point(238, 396);

  77. this.btn_login.Name = «btn_login»;

  78. this.btn_login.Size = new System.Drawing.Size(232, 58);

  79. this.btn_login.TabIndex = 4;

  80. this.btn_login.Text = «LOGIN»;

  81. this.btn_login.UseVisualStyleBackColor = true;

  82. this.btn_login.Click += new System.EventHandler(this.LoginButton);

  83. //

  84. // button1

  85. //

  86. this.button1.Location = new System.Drawing.Point(13, 460);

  87. this.button1.Name = «button1»;

  88. this.button1.Size = new System.Drawing.Size(89, 39);

  89. this.button1.TabIndex = 5;

  90. this.button1.Text = «Register»;

  91. this.button1.UseVisualStyleBackColor = true;

  92. this.button1.Click += new System.EventHandler(this.GoToRegister);

  93. //

  94. // Login

  95. //

  96. this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);

  97. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

  98. this.ClientSize = new System.Drawing.Size(721, 511);

  99. this.Controls.Add(this.button1);

  100. this.Controls.Add(this.btn_login);

  101. this.Controls.Add(this.txt_password);

  102. this.Controls.Add(this.label2);

  103. this.Controls.Add(this.txt_username);

  104. this.Controls.Add(this.label1);

  105. this.Name = «Login»;

  106. this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

  107. this.Text = «LOGIN»;

  108. this.ResumeLayout(false);

  109. this.PerformLayout();

  110. }

  111. #endregion

  112. private System.Windows.Forms.Label label1;

  113. private System.Windows.Forms.TextBox txt_username;

  114. private System.Windows.Forms.Label label2;

  115. private System.Windows.Forms.TextBox txt_password;

  116. private System.Windows.Forms.Button btn_login;

  117. private System.Windows.Forms.Button button1;

  118. }

  119. }

Next create another form then called it as Registration.cs. This is the form for registering an accounts. To do that write these block of codes inside the designer file.

  1. namespace Simple_Registration_and_Login_Application

  2. {

  3. partial class Registration

  4. {

  5. /// <summary>

  6. /// Required designer variable.

  7. /// </summary>

  8. private System.ComponentModel.IContainer components = null;

  9. /// <summary>

  10. /// Clean up any resources being used.

  11. /// </summary>

  12. /// <param name=»disposing»>true if managed resources should be disposed; otherwise, false.</param>

  13. protected override void Dispose(bool disposing)

  14. {

  15. if (disposing && (components != null))

  16. {

  17.                 components.Dispose();

  18. }

  19. base.Dispose(disposing);

  20. }

  21. #region Windows Form Designer generated code

  22. /// <summary>

  23. /// Required method for Designer support — do not modify

  24. /// the contents of this method with the code editor.

  25. /// </summary>

  26. private void InitializeComponent()

  27. {

  28. this.label1 = new System.Windows.Forms.Label();

  29. this.txt_firstname = new System.Windows.Forms.TextBox();

  30. this.label2 = new System.Windows.Forms.Label();

  31. this.txt_lastname = new System.Windows.Forms.TextBox();

  32. this.txt_username = new System.Windows.Forms.TextBox();

  33. this.label3 = new System.Windows.Forms.Label();

  34. this.txt_password = new System.Windows.Forms.TextBox();

  35. this.label4 = new System.Windows.Forms.Label();

  36. this.button1 = new System.Windows.Forms.Button();

  37. this.button2 = new System.Windows.Forms.Button();

  38. this.SuspendLayout();

  39. //

  40. // label1

  41. //

  42. this.label1.AutoSize = true;

  43. this.label1.Font = new System.Drawing.Font(«Arial», 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  44. this.label1.Location = new System.Drawing.Point(100, 93);

  45. this.label1.Name = «label1»;

  46. this.label1.Size = new System.Drawing.Size(139, 32);

  47. this.label1.TabIndex = 0;

  48. this.label1.Text = «Firstname»;

  49. //

  50. // txt_firstname

  51. //

  52. this.txt_firstname.Font = new System.Drawing.Font(«Arial», 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  53. this.txt_firstname.Location = new System.Drawing.Point(256, 90);

  54. this.txt_firstname.Name = «txt_firstname»;

  55. this.txt_firstname.Size = new System.Drawing.Size(276, 40);

  56. this.txt_firstname.TabIndex = 1;

  57. //

  58. // label2

  59. //

  60. this.label2.AutoSize = true;

  61. this.label2.Font = new System.Drawing.Font(«Arial», 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  62. this.label2.Location = new System.Drawing.Point(100, 161);

  63. this.label2.Name = «label2»;

  64. this.label2.Size = new System.Drawing.Size(138, 32);

  65. this.label2.TabIndex = 2;

  66. this.label2.Text = «Lastname»;

  67. //

  68. // txt_lastname

  69. //

  70. this.txt_lastname.Font = new System.Drawing.Font(«Arial», 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  71. this.txt_lastname.Location = new System.Drawing.Point(256, 158);

  72. this.txt_lastname.Name = «txt_lastname»;

  73. this.txt_lastname.Size = new System.Drawing.Size(276, 40);

  74. this.txt_lastname.TabIndex = 3;

  75. //

  76. // txt_username

  77. //

  78. this.txt_username.Font = new System.Drawing.Font(«Arial», 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  79. this.txt_username.Location = new System.Drawing.Point(256, 231);

  80. this.txt_username.Name = «txt_username»;

  81. this.txt_username.Size = new System.Drawing.Size(276, 40);

  82. this.txt_username.TabIndex = 5;

  83. //

  84. // label3

  85. //

  86. this.label3.AutoSize = true;

  87. this.label3.Font = new System.Drawing.Font(«Arial», 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  88. this.label3.Location = new System.Drawing.Point(100, 234);

  89. this.label3.Name = «label3»;

  90. this.label3.Size = new System.Drawing.Size(143, 32);

  91. this.label3.TabIndex = 4;

  92. this.label3.Text = «Username»;

  93. //

  94. // txt_password

  95. //

  96. this.txt_password.Font = new System.Drawing.Font(«Arial», 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  97. this.txt_password.Location = new System.Drawing.Point(256, 295);

  98. this.txt_password.Name = «txt_password»;

  99. this.txt_password.Size = new System.Drawing.Size(276, 40);

  100. this.txt_password.TabIndex = 7;

  101. this.txt_password.UseSystemPasswordChar = true;

  102. //

  103. // label4

  104. //

  105. this.label4.AutoSize = true;

  106. this.label4.Font = new System.Drawing.Font(«Arial», 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  107. this.label4.Location = new System.Drawing.Point(100, 298);

  108. this.label4.Name = «label4»;

  109. this.label4.Size = new System.Drawing.Size(136, 32);

  110. this.label4.TabIndex = 6;

  111. this.label4.Text = «Password»;

  112. //

  113. // button1

  114. //

  115. this.button1.Font = new System.Drawing.Font(«Arial», 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  116. this.button1.Location = new System.Drawing.Point(246, 387);

  117. this.button1.Name = «button1»;

  118. this.button1.Size = new System.Drawing.Size(213, 43);

  119. this.button1.TabIndex = 8;

  120. this.button1.Text = «Register»;

  121. this.button1.UseVisualStyleBackColor = true;

  122. this.button1.Click += new System.EventHandler(this.Register);

  123. //

  124. // button2

  125. //

  126. this.button2.Location = new System.Drawing.Point(12, 455);

  127. this.button2.Name = «button2»;

  128. this.button2.Size = new System.Drawing.Size(85, 34);

  129. this.button2.TabIndex = 9;

  130. this.button2.Text = «Login»;

  131. this.button2.UseVisualStyleBackColor = true;

  132. this.button2.Click += new System.EventHandler(this.GoToLogin);

  133. //

  134. // Registration

  135. //

  136. this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);

  137. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

  138. this.ClientSize = new System.Drawing.Size(702, 501);

  139. this.Controls.Add(this.button2);

  140. this.Controls.Add(this.button1);

  141. this.Controls.Add(this.txt_password);

  142. this.Controls.Add(this.label4);

  143. this.Controls.Add(this.txt_username);

  144. this.Controls.Add(this.label3);

  145. this.Controls.Add(this.txt_lastname);

  146. this.Controls.Add(this.label2);

  147. this.Controls.Add(this.txt_firstname);

  148. this.Controls.Add(this.label1);

  149. this.Name = «Registration»;

  150. this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

  151. this.Text = «Registration»;

  152. this.ResumeLayout(false);

  153. this.PerformLayout();

  154. }

  155. #endregion

  156. private System.Windows.Forms.Label label1;

  157. private System.Windows.Forms.TextBox txt_firstname;

  158. private System.Windows.Forms.Label label2;

  159. private System.Windows.Forms.TextBox txt_lastname;

  160. private System.Windows.Forms.TextBox txt_username;

  161. private System.Windows.Forms.Label label3;

  162. private System.Windows.Forms.TextBox txt_password;

  163. private System.Windows.Forms.Label label4;

  164. private System.Windows.Forms.Button button1;

  165. private System.Windows.Forms.Button button2;

  166. }

  167. }

Lastly, create another form for the home form after logging in called Home.cs. Just write these block of codes inside the designer file.

  1. namespace Simple_Registration_and_Login_Application

  2. {

  3. partial class Home

  4. {

  5. /// <summary>

  6. /// Required designer variable.

  7. /// </summary>

  8. private System.ComponentModel.IContainer components = null;

  9. /// <summary>

  10. /// Clean up any resources being used.

  11. /// </summary>

  12. /// <param name=»disposing»>true if managed resources should be disposed; otherwise, false.</param>

  13. protected override void Dispose(bool disposing)

  14. {

  15. if (disposing && (components != null))

  16. {

  17.                 components.Dispose();

  18. }

  19. base.Dispose(disposing);

  20. }

  21. #region Windows Form Designer generated code

  22. /// <summary>

  23. /// Required method for Designer support — do not modify

  24. /// the contents of this method with the code editor.

  25. /// </summary>

  26. private void InitializeComponent()

  27. {

  28. this.label1 = new System.Windows.Forms.Label();

  29. this.button1 = new System.Windows.Forms.Button();

  30. this.SuspendLayout();

  31. //

  32. // label1

  33. //

  34. this.label1.AutoSize = true;

  35. this.label1.Font = new System.Drawing.Font(«Arial», 26F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

  36. this.label1.Location = new System.Drawing.Point(10, 70);

  37. this.label1.Name = «label1»;

  38. this.label1.Size = new System.Drawing.Size(457, 60);

  39. this.label1.TabIndex = 0;

  40. this.label1.Text = «WELCOME USER»;

  41. //

  42. // button1

  43. //

  44. this.button1.Location = new System.Drawing.Point(174, 242);

  45. this.button1.Name = «button1»;

  46. this.button1.Size = new System.Drawing.Size(119, 31);

  47. this.button1.TabIndex = 1;

  48. this.button1.Text = «Logout»;

  49. this.button1.UseVisualStyleBackColor = true;

  50. this.button1.Click += new System.EventHandler(this.Logout);

  51. //

  52. // Home

  53. //

  54. this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);

  55. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

  56. this.ClientSize = new System.Drawing.Size(479, 325);

  57. this.Controls.Add(this.button1);

  58. this.Controls.Add(this.label1);

  59. this.Name = «Home»;

  60. this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;

  61. this.Text = «Home»;

  62. this.ResumeLayout(false);

  63. this.PerformLayout();

  64. }

  65. #endregion

  66. private System.Windows.Forms.Label label1;

  67. private System.Windows.Forms.Button button1;

  68. }

  69. }

or also you create the layout by dragging the proper tools to the forms.

Creating the Script

We will now create the script to make things work. To do that go to the csharp script called Registration.cs then right click and select view code, this will force you to go to the text editor. Then write these block of codes inside the Class of the form.

  1. using System;

  2. using System.Collections.Generic;

  3. using System.ComponentModel;

  4. using System.Data;

  5. using System.Drawing;

  6. using System.Linq;

  7. using System.Text;

  8. using System.Threading.Tasks;

  9. using System.Windows.Forms;

  10. using System.Data.SQLite;

  11. namespace Simple_Registration_and_Login_Application

  12. {

  13. public partial class Registration : Form

  14. {

  15.         SQLiteConnection conn;

  16. String connectString;

  17. public Registration()

  18. {

  19.             InitializeComponent();

  20.             connectString = @»Data Source=» + Application.StartupPath + @»\Database\login.db; version=3″;

  21. }

  22. private void Register(object sender, EventArgs e) {

  23. using (conn = new SQLiteConnection(connectString)) {

  24. try {

  25. if (txt_username.Text != «» || txt_password.Text != «»)

  26. {

  27.                         SQLiteCommand cmd = new SQLiteCommand();

  28.                         cmd.CommandText = @»INSERT INTO member (firstname, lastname, username, password) VALUES(@firstname, @lastname, @username, @password)»;

  29.                         cmd.Connection = conn;

  30.                         cmd.Parameters.Add(new SQLiteParameter(«@firstname», txt_firstname.Text));

  31.                         cmd.Parameters.Add(new SQLiteParameter(«@lastname», txt_lastname.Text));

  32.                         cmd.Parameters.Add(new SQLiteParameter(«@username», txt_username.Text));

  33.                         cmd.Parameters.Add(new SQLiteParameter(«@password», txt_password.Text));

  34.                         conn.Open();

  35. int i = cmd.ExecuteNonQuery();

  36. if (i == 1)

  37. {

  38.                             MessageBox.Show(«Successfully Created!»);

  39.                             txt_firstname.Text = «»;

  40.                             txt_lastname.Text = «»;

  41.                             txt_username.Text = «»;

  42.                             txt_password.Text = «»;

  43. }

  44. }

  45. else {

  46.                         MessageBox.Show(«Required Fields!»);

  47. }

  48. }

  49. catch (Exception ex) {

  50.                     MessageBox.Show(ex.Message);

  51. }

  52. }

  53. }

  54. private void GoToLogin(object sender, EventArgs e) {

  55.             Login login = new Login();

  56. this.Close();

  57.             login.Show();

  58. }

  59. }

  60. }

Next, go to the other scripts then write the code provided below corresponded to the name of the scripts.
Login.cs

  1. using System;

  2. using System.Collections.Generic;

  3. using System.ComponentModel;

  4. using System.Data;

  5. using System.Drawing;

  6. using System.Linq;

  7. using System.Text;

  8. using System.Threading.Tasks;

  9. using System.Windows.Forms;

  10. using System.Data.SQLite;

  11. namespace Simple_Registration_and_Login_Application

  12. {

  13. public partial class Login : Form

  14. {

  15.         SQLiteConnection conn;

  16.         SQLiteCommand cmd;

  17. String connectString;

  18.         SQLiteDataReader rd;

  19. public Login()

  20. {

  21.             InitializeComponent();

  22.             connectString = @»Data Source=» + Application.StartupPath + @»\Database\login.db;version=3″;

  23. }

  24. private void LoginButton(object sender, EventArgs e) {

  25. if (txt_username.Text == «» || txt_password.Text == «») {

  26.                 MessageBox.Show(«Required Fields!»);

  27. }

  28. else {

  29. using (conn = new SQLiteConnection(connectString))

  30. {

  31. try

  32. {

  33.                         conn.Open();

  34. string query = «SELECT * FROM member WHERE username='» + txt_username.Text + «‘ AND password='» + txt_password.Text + «‘»;

  35.                         cmd = new SQLiteCommand(query, conn);

  36.                         cmd.ExecuteNonQuery();

  37.                         rd = cmd.ExecuteReader();

  38. int row = 0;

  39. while (rd.Read())

  40. {

  41.                             row++;

  42. }

  43. if (row == 1)

  44. {

  45.                             MessageBox.Show(«Successfully Login»);

  46.                             Home home = new Home();

  47. this.Hide();

  48.                             home.Show();

  49. }

  50. else

  51. {

  52.                             MessageBox.Show(«Invalid username or password!»);

  53. }

  54. }

  55. catch (Exception ex)

  56. {

  57.                         MessageBox.Show(ex.Message);

  58. }

  59. }

  60. }

  61. }

  62. private void GoToRegister(object sender, EventArgs e) {

  63.             Registration registration = new Registration();

  64. this.Hide();

  65.             registration.Show();

  66. }

  67. }

  68. }

Home.cs

  1. using System;

  2. using System.Collections.Generic;

  3. using System.ComponentModel;

  4. using System.Data;

  5. using System.Drawing;

  6. using System.Linq;

  7. using System.Text;

  8. using System.Threading.Tasks;

  9. using System.Windows.Forms;

  10. namespace Simple_Registration_and_Login_Application

  11. {

  12. public partial class Home : Form

  13. {

  14. public Home()

  15. {

  16.             InitializeComponent();

  17. }

  18. private void Logout(object sender, EventArgs e) {

  19.             Login login = new Login();

  20. this.Close();

  21.             login.Show();

  22. }

  23. }

  24. }

Try to run the application and see if it works.

There you go we successfully created a Simple Registration And Login Application using C#. I hope that this tutorial help you understand on how to develop an application using C#. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Comments

Add new comment

  • 3845 views

Login-and-Register-System

Login and Register System using C# for Windows Forms

Technologies   |   
How to use   |   
License

🧪 technologies

This project was built using the following technologies and features:

  • C#
  • PostgreSQL
  • NpgSql
  • Visual Studio IDE

💡 how to use

  • Clone the repository.
  • Open the project from Visual Studio 2022.
  • Rename the file from APP_config.xml to app.config and in the below code section type your database credentials.
<appSettings>
		<add key="MyConnection" value="Server=localhost;Port=5432;Database=yourDataBase;User Id=postgres;Password=yourPassword;" />
	</appSettings>
  • Database structure.

For this application, we are using A local PostgreSQL Database.

Table name : csharp_user

create TABLE IF NOT EXISTS csharp_user(
    id Serial ,
    username VARCHAR NOT NULL,
    password VARCHAR NOT NULL,
    PRIMARY KEY (id)
)
INSERT into csharp_user(username,password) values('admin', 'admin') 

system

📄 License

This project was built under MIT. See the file LICENSE for more details.


Hey Guys,

It’s long time to see you again with this post. I am in new team and i would like to share my experience that i have gained in my previous team, where i work mostly with windows Form, SQL, Controls, ASP.NET, JS and lot more interesting…

Let’s start this with a simple registration form using Windows Form C# or VB with back end MS Access to store the data. Programmer have come across creating a simple registration Form in there life, either in there work or to learn as an example !! Its looks like simple but it has complication too !!! Let me make it easy to make programmer who haven’t tried so far or those who are interested to learn !!

Window Form journey in designing the registration form !! 

1. Windows Form can be created using Visual Studio and this example can be created either from Visual Studio 2005 to 2015 as your wish !!

2. If  you dont have visual Studio , Please download Visual studio express for free from the link.

3. Once installed , Open the Visual studio IDE and click on New project in the getting started page or File -> New Project. A page with project list will be opened.

Getting Started !!!

Getting Started !!!

4. Click okay to create an Empty Windows Form Application.

Designing the Simple Registration Form in Windows Form !! 

1. Use the toolbar like Label , Text box , button to design the form as given below.

    • Login Page

Login Page

Login Page

    • Main Page – Panel 1

Main Page

Main Page

    • Data Grid View Page – Panel 2

Data Grid View

Data Grid View

2. How to design the registration Form in Single pages and that will provide vision like navigation from screen to screen. I have used the panel upon the designed content to provided the visuals.

3. I suggest you to design the Login Form First then apply a Panel – 1 on it and design the Registration form and the same for Data Grid View Page.

4. When form loads , hide the panels and make the flow visible. Please refer the below code for your reference.

Here is the C# Code:

public partial class Form1 : Form
    {
        OleDbConnection connect = new OleDbConnection(&amp;quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source='../../sample2.mdb'&amp;quot;);
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == &amp;quot;admin&amp;quot; &amp;amp;&amp;amp; textBox2.Text == &amp;quot;adminpass&amp;quot;)
            {
                this.panel1.Show();
                this.panel2.Hide();
                this.textBox1.Clear();
                this.textBox2.Clear();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != &amp;quot;&amp;quot; || textBox2.Text != &amp;quot;&amp;quot;)
            {
                textBox1.Clear();
                textBox2.Clear();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.panel1.Hide();

            //Open the connection.
            connect.Open();

            //Use a variable to hold the SQL statement.
            string selectString = &amp;quot;SELECT ID,Name,Department FROM Sample&amp;quot;;

            //Create an OleDbCommand object.
            //Notice that this line passes in the SQL statement and the OleDbConnection object
            OleDbCommand cmd = new OleDbCommand(selectString, connect);
            OleDbDataReader reader = cmd.ExecuteReader();
            if (!(reader.HasRows))
            {
                textBox4.Text = &amp;quot;1&amp;quot;;
            }
            else
            {
                while (reader.Read())
                {
                    this.label11.Text = reader[&amp;quot;ID&amp;quot;].ToString();
                    textBox4.Text = (Convert.ToInt16(reader[&amp;quot;ID&amp;quot;]) + 1).ToString();
                }
            }
            reader.Close();
            connect.Close();
            ClearAll();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            this.panel1.Hide();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ClearAll();
        }

        private void ClearAll()
        {
            //Clear
            textBox3.Clear();
            textBox7.Clear();
            textBox5.Clear();
            textBox6.Clear();
            comboBox1.SelectedItem = this.comboBox1.Items[0];
            comboBox2.SelectedItem = this.comboBox2.Items[0];
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //Register
            try
            {

                int id = Convert.ToInt16(textBox4.Text);
                string name = textBox3.Text;
                string college = textBox7.Text;
                string department = comboBox2.SelectedItem.ToString();
                int passedOut = Convert.ToInt32(comboBox1.SelectedItem.ToString());
                string mailId = textBox5.Text;

                double contactNo = Convert.ToDouble(textBox6.Text);


                OleDbCommand cmd = new OleDbCommand(&amp;quot;INSERT into sample (ID,Name,Department,College,PassedOut,MailId,ContactNo) Values(@id,@name,@department,@college,@passedOut,@mailId,@contactNo)&amp;quot;, connect);

                connect.Open();
                if (connect.State == ConnectionState.Open)
                {
                    cmd.Parameters.Add(&amp;quot;@id&amp;quot;, OleDbType.Integer).Value = id;
                    cmd.Parameters.Add(&amp;quot;@name&amp;quot;, OleDbType.VarChar).Value = name;
                    cmd.Parameters.Add(&amp;quot;@department&amp;quot;, OleDbType.VarChar).Value = department;
                    cmd.Parameters.Add(&amp;quot;@college&amp;quot;, OleDbType.VarChar).Value = college;
                    cmd.Parameters.Add(&amp;quot;@passedOut&amp;quot;, OleDbType.Integer).Value = passedOut;
                    cmd.Parameters.Add(&amp;quot;@mailId&amp;quot;, OleDbType.VarChar).Value = mailId;
                    cmd.Parameters.Add(&amp;quot;@contactNo&amp;quot;, OleDbType.Double).Value = contactNo;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        MessageBox.Show(&amp;quot;Data Registered !!&amp;quot;);
                        connect.Close();
                        UpdateView(id);
                        ClearAll();
                    }
                    catch (OleDbException ex)
                    {
                        MessageBox.Show(ex.Source);
                        connect.Close();
                    }
                    //Clear All
                }
                else
                {
                    MessageBox.Show(&amp;quot;Connection Failed&amp;quot;);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString() + &amp;quot;Provide Correct details&amp;quot;);
            }
        }

        private void UpdateView(int id)
        {
            this.label11.Text = textBox4.Text;
            textBox4.Text = (Convert.ToInt16(textBox4.Text) + 1).ToString();
            this.panel1.Refresh();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            connect.Open();

            //Use a variable to hold the SQL statement.
            string selectString = &amp;quot;SELECT * FROM Sample&amp;quot;;

            //Create an OleDbCommand object.
            //Notice that this line passes in the SQL statement and the OleDbConnection object
            OleDbCommand cmd = new OleDbCommand(selectString, connect);
            OleDbDataAdapter adp = new OleDbDataAdapter(selectString, connect);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            this.dataGridView1.DataSource = dt;
            panel2.Show();
            connect.Close();

        }

        private void button7_Click(object sender, EventArgs e)
        {
            panel2.Hide();
        }
    }

Here is the VB code :

 Partial Public Class Form1
	 Inherits Form
		Private connect As New OleDbConnection(&amp;quot;Provider=Microsoft.Jet.OLEDB.4.0;Data Source='../../sample2.mdb'&amp;quot;)
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button2_Click(ByVal sender As Object, ByVal e As EventArgs)
			If textBox1.Text = &amp;quot;admin&amp;quot; AndAlso textBox2.Text = &amp;quot;adminpass&amp;quot; Then
				Me.panel1.Show()
				Me.panel2.Hide()
				Me.textBox1.Clear()
				Me.textBox2.Clear()
			End If
		End Sub

		Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
			If textBox1.Text &amp;lt;&amp;gt; &amp;quot;&amp;quot; OrElse textBox2.Text &amp;lt;&amp;gt; &amp;quot;&amp;quot; Then
				textBox1.Clear()
				textBox2.Clear()
			End If
		End Sub

		Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
			Me.panel1.Hide()

			'Open the connection.
			connect.Open()

			'Use a variable to hold the SQL statement.
			Dim selectString As String = &amp;quot;SELECT ID,Name,Department FROM Sample&amp;quot;

			'Create an OleDbCommand object.
			'Notice that this line passes in the SQL statement and the OleDbConnection object
			Dim cmd As New OleDbCommand(selectString, connect)
			Dim reader As OleDbDataReader = cmd.ExecuteReader()
			If Not(reader.HasRows) Then
				textBox4.Text = &amp;quot;1&amp;quot;
			Else
				Do While reader.Read()
					Me.label11.Text = reader(&amp;quot;ID&amp;quot;).ToString()
					textBox4.Text = (Convert.ToInt16(reader(&amp;quot;ID&amp;quot;)) + 1).ToString()
				Loop
			End If
			reader.Close()
			connect.Close()
			ClearAll()
		End Sub

		Private Sub button5_Click(ByVal sender As Object, ByVal e As EventArgs)
			Me.panel1.Hide()
		End Sub

		Private Sub button4_Click(ByVal sender As Object, ByVal e As EventArgs)
			ClearAll()
		End Sub

		Private Sub ClearAll()
			'Clear
			textBox3.Clear()
			textBox7.Clear()
			textBox5.Clear()
			textBox6.Clear()
			comboBox1.SelectedItem = Me.comboBox1.Items(0)
			comboBox2.SelectedItem = Me.comboBox2.Items(0)
		End Sub

		Private Sub button3_Click(ByVal sender As Object, ByVal e As EventArgs)
			'Register
			Try

				Dim id As Integer = Convert.ToInt16(textBox4.Text)
				Dim name As String = textBox3.Text
				Dim college As String = textBox7.Text
				Dim department As String = comboBox2.SelectedItem.ToString()
				Dim passedOut As Integer = Convert.ToInt32(comboBox1.SelectedItem.ToString())
				Dim mailId As String = textBox5.Text

				Dim contactNo As Double = Convert.ToDouble(textBox6.Text)


				Dim cmd As New OleDbCommand(&amp;quot;INSERT into sample (ID,Name,Department,College,PassedOut,MailId,ContactNo) Values(@id,@name,@department,@college,@passedOut,@mailId,@contactNo)&amp;quot;, connect)

				connect.Open()
				If connect.State = ConnectionState.Open Then
					cmd.Parameters.Add(&amp;quot;@id&amp;quot;, OleDbType.Integer).Value = id
					cmd.Parameters.Add(&amp;quot;@name&amp;quot;, OleDbType.VarChar).Value = name
					cmd.Parameters.Add(&amp;quot;@department&amp;quot;, OleDbType.VarChar).Value = department
					cmd.Parameters.Add(&amp;quot;@college&amp;quot;, OleDbType.VarChar).Value = college
					cmd.Parameters.Add(&amp;quot;@passedOut&amp;quot;, OleDbType.Integer).Value = passedOut
					cmd.Parameters.Add(&amp;quot;@mailId&amp;quot;, OleDbType.VarChar).Value = mailId
					cmd.Parameters.Add(&amp;quot;@contactNo&amp;quot;, OleDbType.Double).Value = contactNo
					Try
						cmd.ExecuteNonQuery()
						MessageBox.Show(&amp;quot;Data Registered !!&amp;quot;)
						connect.Close()
						UpdateView(id)
						ClearAll()
					Catch ex As OleDbException
						MessageBox.Show(ex.Source)
						connect.Close()
					End Try
					'Clear All
				Else
					MessageBox.Show(&amp;quot;Connection Failed&amp;quot;)
				End If
			Catch ex As Exception
				MessageBox.Show(ex.ToString() &amp;amp; &amp;quot;Provide Correct details&amp;quot;)
			End Try
		End Sub

		Private Sub UpdateView(ByVal id As Integer)
			Me.label11.Text = textBox4.Text
			textBox4.Text = (Convert.ToInt16(textBox4.Text) + 1).ToString()
			Me.panel1.Refresh()
		End Sub

		Private Sub button6_Click(ByVal sender As Object, ByVal e As EventArgs)
			connect.Open()

			'Use a variable to hold the SQL statement.
			Dim selectString As String = &amp;quot;SELECT * FROM Sample&amp;quot;

			'Create an OleDbCommand object.
			'Notice that this line passes in the SQL statement and the OleDbConnection object
			Dim cmd As New OleDbCommand(selectString, connect)
			Dim adp As New OleDbDataAdapter(selectString, connect)
			Dim dt As New DataTable()
			adp.Fill(dt)
			Me.dataGridView1.DataSource = dt
			panel2.Show()
			connect.Close()

		End Sub

		Private Sub button7_Click(ByVal sender As Object, ByVal e As EventArgs)
			panel2.Hide()
		End Sub
 End Class

Here is the Screen short of the MS Access :

MS Access Design View

MS Access Design View

5. Also i also like to mention the method to find the connection string of the database (MDF,SDF,,mdb) using server explorer.

6. Click View -> Server Explorer (Ctrl + Alt+S) open the server explorer.

7. Right click on the Data Connection -> Add Connection -> Change -> Microsoft Access Database File -> Click Ok.

6

7

8. Click Browse to select the (mdf, sdf,mdb) file and Test the connection and it will return Success. This will provide result that the database is linked with server explorer.

8

9

9. After click OK then the Database can be accessed using the server explorer and we can view the database , data , modification can be done here !!  We can see the connection string of the database in the property panel, Which is used to connect the application to the DB !!!

10

10. Here is the sample which i coded to write this post , this will certainly help you to understand better !!

Feel free to post you comment and suggestions , this will help me to provide a detail blog in the future 🙂 Meet you with one more interesting codes and concepts !!!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Пропали значки панели задач windows 10 решение
  • Как настроить порты в windows server
  • Бесплатный гипервизор для windows
  • Heif extension for windows 10
  • Настройка ssh windows server 2016