Three times wrong login credentials then login form will exit

In this blog we will know if a user provides three times wrong login credentials then the login form will be closed.

 

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.OleDb;

namespace Invalid_login_three_times

{

    public partial class Form1 : Form

    {

        string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["dsn"];

        OleDbCommand com;

        OleDbDataAdapter oledbda;

        DataSet ds;

        DataTable dt;

        string str;

        string s1;

        int Counter=0;

        int i = 0;

        int j = 0;

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void btn_login_Click(object sender, EventArgs e)

        {

            if ((txt_userid.Text == "") && (txt_password.Text==""))

            {

                MessageBox.Show("Userid and Password cannot be blank");

                txt_userid.Focus();

                return;

            }

 

            Counter = Counter + 1;

            if ((Counter < 3))

            {

                j = dt.Rows.Count - 1;

                for (i = 0; i <= j; i++)

            {

                if ((txt_userid.Text == dt.Rows[i].ItemArray[0].ToString() & txt_password.Text == dt.Rows[i].ItemArray[1].ToString()))

            {

                    MessageBox.Show("Userid and Password are correct");

                    this.Close();

            }

                    else

                {

                    s1 = Convert.ToString(3 - Counter);

                  

                } 

            }

                MessageBox.Show("Userid or Password are incorrect! You have " + s1 + " tries left.");      

            }

 

            else

            {

                MessageBox.Show("Userid or Password are incorrect! You have no attempts left");

                Application.Exit();

            }

            clear();

        }

 

        void clear()

        {

            txt_userid.Text = "";

            txt_password.Text = "";

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            OleDbConnection con = new OleDbConnection(ConnectionString);

            try

            {

                con.Open();

                str = "select * from login";

                com = new OleDbCommand(str, con);

                oledbda = new OleDbDataAdapter(com);

                ds = new DataSet();

                oledbda.Fill(ds, "login");

                con.Close();

                dt = ds.Tables["login"];

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

    }

}

 

 

Thanks for reading