Tuesday, September 17, 2013

Login Form in a Windows Forms Application

The Form Shape : 



// there is 2 Labels, 2 TextBoxes, 2 Buttons, the first TextBox is named : txtUserName , the second TextBox is named : txtPassword, the Log In Button is named : btnLogin, and the Clear Button is named : BtnClear 

The Table in the database : 



// The table named is : LogIn_T 

In the Table Data i added a user name and a password : 



The Log In Button code : 

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if(txtUserName.Text == string.Empty && txtPassword.Text == string.Empty)
            {
                MessageBox.Show("please enter a user name and a password", "Alert", MessageBoxButtons.OK);
            }
            else if (txtUserName.Text == string.Empty && txtPassword.Text != string.Empty)
            {
                MessageBox.Show("please enter a username", "Alert", MessageBoxButtons.OK);
            }
            else if (txtUserName.Text != string.Empty && txtPassword.Text == string.Empty)
            {
                MessageBox.Show("please enter a password", "Alert", MessageBoxButtons.OK);
            }
            else if (txtUserName.Text != string.Empty && txtPassword.Text != string.Empty)
            {
                SqlConnection Con = new SqlConnection();
                Con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Saleem\Documents\Project.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
                Con.Open();
                String query = "SELECT UserName, Password From LogIn_T WHERE UserName = @UserName AND Password = @Password" ;
                SqlCommand com = new SqlCommand(query, Con);
                com.Parameters.AddWithValue("@UserName", txtUserName.Text);
                com.Parameters.AddWithValue("@Password", txtPassword.Text);
                SqlDataReader reader = com.ExecuteReader();
                if (reader.Read())
                {
                    // show the form you want
                    Form2 form2 = new Form2();
                    form2.Show();
                    this.Hide();
                }
                else
                {
                    MessageBox.Show("invalid username or password", "Alert", MessageBoxButtons.OK);
                }
              reader.Close();
              Con.Close();
            }
        }

The Clear Button Code : 

        private void BtnClear_Click(object sender, EventArgs e)
        {
            txtUserName.Text = string.Empty;
            txtPassword.Text = string.Empty;
        }



Testing : 

1 - Not entering a username and a password : 






2- Not entering a user name : 



3- Not entering a password : 



4- Invalid username : 


5- Invalid password : 


6- Invalid username and password : 


7- Valid username and password : 

Form2 opens : 


No comments :

Post a Comment