Friday, 16 January 2015

Simple Windows Form Login Application in C#

In this Post, we will learn how to create a Simple Windows form Login application.

Let’s Begin:
1. Create a New Windows Form Application.
Create Windows Form Application
2. Add New Database (I have created a database named as MyDatabase.mdf). Add a table (named as tbl_Login). The following is the table schema for creating tbl_Login.
Table Structure
3. Create a form (frmLogin) and add Label, TextBox and button control from the Toolbox.
Login Form
4. Add another Windows Form and named it as frmMain. This form will be shown to the user after successful Login by the user.
Main Form
Now, Go to frmLogin.cs code and add System.Data and System.Data.SqlClient namespace. Double click on btn_Submit to create btn_Submit Click event.
frmLogin.cs Code:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace LoginApplication
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
        }
        //Connection String
        string cs = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True;";
        //btn_Submit Click event
        private void button1_Click(object sender, EventArgs e)
        {
            if(txt_UserName.Text=="" || txt_Password.Text=="")
            {
                MessageBox.Show("Please provide UserName and Password");
                return;
            }
            try
            {
                //Create SqlConnection
                SqlConnection con = new SqlConnection(cs);
                SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName=@username and Password=@password",con);
                cmd.Parameters.AddWithValue("@username",txt_UserName.Text);
                cmd.Parameters.AddWithValue("@password", txt_Password.Text);
                con.Open();
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapt.Fill(ds);
                con.Close();
                int count = ds.Tables[0].Rows.Count;
                //If count is equal to 1, than show frmMain form
                if (count == 1)
                {
                    MessageBox.Show("Login Successful!");
                    this.Hide();
                    frmMain fm = new frmMain();
                    fm.Show();
                }
                else
                {
                    MessageBox.Show("Login Failed!");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
After that, go to frmMain.cs form and create btn_LogOut click event. On clicking the Logout button, frmMain form hides and show frmLogin form.

frmMain.cs Code:
using System;
using System.Windows.Forms;

namespace LoginApplication
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
        //btn_LogOut Click Event
        private void btn_LogOut_Click(object sender, EventArgs e)
        {
            this.Hide();
            frmLogin fl = new frmLogin();
            fl.Show();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

    }
}
Final Preview:
Windows form login application
Hope you like it. Thanks.
[Download Source Code via Google Drive]

30 comments:

  1. Will it work in sharpdevelop?

    ReplyDelete
    Replies
    1. Yes, It will work fine in SharpDevelop. Just follow each step / instruction shown in this article.

      Delete
    2. this article Very Helpful for us. thanks brother

      Delete
    3. please check my blog to http://www.toufik.web.id

      Delete
  2. Replies
    1. Hi DJ, Add Username and Password in tbl_Login (Table) and use that for login purpose.

      Delete
  3. hello guys, this is sooo cool, dear Dj the password is verified in the database but you can create an other form of add user just for the admin.

    I'm a .Net fun as i find this blog we will continue sharing ideas and knowledge.

    keep it up!

    ReplyDelete
  4. Hi, how can we do the step number 2. please help. newbie here

    ReplyDelete
    Replies
    1. In Step second, You have to create a database (named it as MyDatabase). After that add a table (named as tbl_Login).

      Delete
  5. If you enter in the main form, clic on the "Log Out" button, it returns to the login screen (that's ok) but there, if you clic on the cross to close the window, the program hides the login screen (that's ok) but it never ends ! you need to go to Debug/Terminate ALl to kill it

    Domi.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  6. Hello Domingue:

    Create function:

    private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
    {
    Application.Exit();
    }

    and "frmLogin.Designer.cs"
    add:

    this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmLogin_FormClosing);

    Perdone por mi mal ingles, Solo Hablo español.-

    Saludos.-
    Miguel Angel Carpio.-
    VE.

    ReplyDelete
  7. frmMain fm = new frmMain();

    Error The call is ambiguous between the following methods or properties: 'WindowsFormsApplication1.frmMain.frmMain()' and 'WindowsFormsApplication1.frmMain.frmMain()'

    ReplyDelete
  8. I've tried using this but my 'cs' variable is showing an error and I'm not sure how to fix it.

    ReplyDelete
    Replies
    1. I've fixed this error but now I get another error when I try and enter any values saying "A network-related or instance-specific error occurred while establishing a connection to SQL Server."

      Delete
    2. Go to your services in your windows and turn sql server on. I think that is your problem Sam! :)

      Delete
  9. thank you , but how can i do if i want to have all information about user connected on all form ?

    ReplyDelete
  10. My Main Page have Two Links(admin & User)
    whenever click admin link --admin login window is opened enter the username and password then login is success status page is opened. same as User also same success login then get status page is opened status page is common. but status page is having back button whenever click the back button appropriate login page is opened(admin as well as user). how to do that.

    ReplyDelete

  11. When adding data into the Login table, what do we have to put in the ID row ?

    ReplyDelete
    Replies
    1. Go to your database login table, go to the properties and then search for Identity specification and click the 'plus' then you set it to true. Save your table and now add a username and a password. The id will be automaticly set now. Sorry for this late reply I hope you have your answer already :)

      Delete

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Subscribe us on YouTube

Like us on Facebook

Follow us on Google+