2015-07-12 76 views
0

我想在用户签署注册表格时检查一些项目(唯一的用户名,类似的两个密码输入,电子邮件的有效性,而不是空字段)这是我的代码。但不适用于空白字段。哪里有问题?!验证C#空字段

private void button1_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      //Check Username: if username is unavailable, goto catch and continue register 
      var q = (from c in Session.DB.Guests 
        where c.UserName == textBox4.Text 
        select c).Single(); 
      MessageBox.Show("UserName is Not Available"); 
     } 
     catch 
     { 
      try 
      { // Here My code For Blank Fields: 
       if (!(textBox1.Text == null && textBox2.Text == null && textBox3.Text == null && 
       textBox4.Text == null && textBox5.Text == null && textBox6.Text == null)) 

        if (!(textBox5.Text.Contains(textBox4.Text) || textBox5.Text != textBox6.Text)) //Check Password 
         if (textBox3.Text.Contains("@") && textBox3.Text.Contains(".")) 
         { 
          Controller.UserController.RegisterUser(textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text 
           , textBox5.Text); 
          MessageBox.Show("Register!"); 
         } 

        else 
         MessageBox.Show("Incorrect email address"); 
       else 
        MessageBox.Show("Password Not match or contains username"); 
       else MessageBox.Show("Empty Fields! All Fields Required!"); 
      } 
      catch 
      { 
       MessageBox.Show("Error"); 
      } 
     }} 
+1

为什么主要代码写在catch块? catch块会在出现异常(错误)的地方出现。问题的标题也是误导性的。请纠正。 – Spidey

+0

@Nimesh我在每种情况下使用try catch来处理错误,它是否是false? – Mahsa

回答

0

我想你错过了你的代码中的一些逻辑。另外,你应该尽量避免使用try-catch块,并且应该尝试给你的控件赋予有意义的名字,这会让你的代码更具可读性。试着这样做:

// textBox4 should be txtUserName for example, it's more intuitive 
var q = (from c in Session.DB.Guests 
     where c.UserName == textBox4.Text 
     select c).SingleOrDefault(); 

if (q == null) 
{ 
    MessageBox.Show("UserName is Not Available"); 
} 
else 
{ 
    if (textBox1.Text == null || textBox2.Text == null || textBox3.Text == null || 
     textBox4.Text == null || textBox5.Text == null || textBox6.Text == null) 
    { 
     MessageBox.Show("Empty Fields! All Fields Required!"); 
    } 
    else 
    { 
     // textBox5 should be txtPassword and textBox6 should be txtConfirmPassword 
     if (textBox5.Text.Contains(textBox4.Text) || textBox5.Text != textBox6.Text) 
     { 
      MessageBox.Show("Password Not match or contains username"); 
     } 
     else 
     { 
      // textBox3 should be txtEmail, also you should try to find some existing Regex to validate your email 
      if (!textBox3.Text.Contains("@") || !textBox3.Text.Contains(".")) 
      { 
       MessageBox.Show("Incorrect email address"); 
      } 
      else 
      { 
       Controller.UserController.RegisterUser(textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text); 
       MessageBox.Show("Register!"); 
      } 
     } 
    } 
}