2016-10-11 89 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