如果不满足语句,如何阻止代码运行

时间:2016-10-11 15:28:20

标签: c#

你好,我有一个表单,让用户创建一个用户名和密码,使他们能够访问该程序,但如果用户没有在textBox中输入任何内容,它仍然授予他们访问权限我想到了一个解决方案,它给了没有输入任何内容但仍然会创建空白用户的错误。这是代码

    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();
        }
        }

1 个答案:

答案 0 :(得分:2)

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