Chinonso Eke
Chinonso Eke

Reputation: 23

How to stop a code from running if a statement isn't met

Hello please I have a form which makes a user create a username and password to enable them access the program but if the user doesn't type anything inside the textBox it still grants them access I thought of a solution, it gives the error that nothing is typed but it still creates the blank user. Here is the code

    private void button2_Click(object sender, EventArgs e)
        {

             try
            {
                if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
                {
                    MessageBox.Show("Please type in all the fields", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }

                if (textBox2.Text == textBox3.Text)
                {
                    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\User\Desktop\New Project\Project\Project\AdminLogin.mdf;Integrated Security=True;User Instance=True");
                    con.Open();
                    SqlCommand cmd = new SqlCommand(@"INSERT INTO AdminLogin
                         (ADMIN, PASSWORD)
VALUES        ('" + textBox1.Text + "', '" + textBox2.Text + "')", con);
                    cmd.ExecuteNonQuery();
                    con.Close();

                    MessageBox.Show("Welcome, " + textBox1.Text + "", "New Staff", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }


                else 
                    {
                        MessageBox.Show("Passwords do not match", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                }

            }
            catch
            {
                MessageBox.Show("Admin already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
            AdminLogin pl = new AdminLogin();
            pl.Show();
        }
        }

Upvotes: 0

Views: 61

Answers (1)

mybirthname
mybirthname

Reputation: 18137

if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
    MessageBox.Show("Please type in all the fields", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    return; // instead of break;
}

Upvotes: 2

Related Questions