2016-10-11 6 views
0

こんにちは私はユーザーがプログラムにアクセスできるようにユーザー名とパスワードを作成するフォームを用意していますが、私は解決策を考えてアクセス権を与えていますが、何も入力されていないのに空白のユーザーが作成されるというエラーが表示されます。 `、それはあなたのコードを終了します。ここでは、代わりにあなたの妥当性チェックで` break`のコードステートメントが満たされない場合にコードが実行されないようにする方法

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

あなただけの '返すことができます。 –

答えて

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

@ Chinonsoあなたは正しい答えを出すことができます。 – mybirthname

関連する問題