2016-10-11 179 views
0

您好请我有一个窗体,使用户创建一个用户名和密码,使他们能够访问该程序,但如果用户不在文本框内输入任何内容它仍然允许他们访问我想到的解决方案,它给出了没有输入任何内容的错误,但它仍然创建空白用户。下面是代码如何停止代码运行,如果不满足语句

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

而不是'break'在你的验证检查,你可能只是'返回;'这将退出你的代码。 –

回答

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; 
} 
+1

我认为最好把textBox.Text ==“”改为!String.IsNullOrWhiteSpace(textBox.Text),因为你不想接受空格 – Sparrow

+0

我发现一个解决方案谢谢你。 –

+0

@ChinonsoEke没关系,你可以回答正确。 – mybirthname