2011-08-03 25 views
1

我试图找出一种方法来显示我的应用程序中使用MessageBox.Show验证错误的列表。到目前为止,我有这样的:显示MessageBox中的错误列表显示方法

private bool FormIsValid() 
    { 
     bool isValid = true; 
     List<string> strErrors = new List<string>(); 

     if (!(txtFirstName.Text.Length > 1) || !(txtLastName.Text.Length > 1)) 
     { 
      strErrors.Add("You must enter a first and last name."); 
      isValid = false; 
     } 
     if (!txtEmail.Text.Contains("@") || !txtEmail.Text.Contains(".") || !(txtEmail.Text.Length > 5)) 
     { 
      strErrors.Add("You must enter a valid email address."); 
      isValid = false; 
     } 
     if (!(txtUsername.Text.Length > 7) || !(pbPassword.Password.Length > 7) || !ContainsNumberAndLetter(txtUsername.Text) || !ContainsNumberAndLetter(pbPassword.Password)) 
     { 
      strErrors.Add("Your username and password most both contain at least 8 characters and contain at least 1 letter and 1 number."); 
      isValid = false; 
     } 

     if (isValid == false) 
     { 
      MessageBox.Show(strErrors); 
     } 

     return isValid; 
    } 

但是,唉,你不能用String类型的列表显示方法内。有任何想法吗?

回答

5

您可以使用下列内容:

 List<string> errors = new List<string>(); 
     errors.Add("Error 1"); 
     errors.Add("Error 2"); 
     errors.Add("Error 3"); 

     string errorMessage = string.Join("\n", errors.ToArray()); 
     MessageBox.Show(errorMessage); 
2

为什么不使用字符串?

private bool FormIsValid() 
{ 
    bool isValid = true; 
    string strErrors = string.Empty; 

    if (!(txtFirstName.Text.Length > 1) || !(txtLastName.Text.Length > 1)) 
    { 
     strErrors = "You must enter a first and last name."; 
     isValid = false; 
    } 
    if (!txtEmail.Text.Contains("@") || !txtEmail.Text.Contains(".") || !(txtEmail.Text.Length > 5)) 
    { 
     strErrors += "\nYou must enter a valid email address."; 
     isValid = false; 
    } 
    if (!(txtUsername.Text.Length > 7) || !(pbPassword.Password.Length > 7) || !ContainsNumberAndLetter(txtUsername.Text) || !ContainsNumberAndLetter(pbPassword.Password)) 
    { 
     strErrors += "\nYour username and password most both contain at least 8 characters and contain at least 1 letter and 1 number."; 
     isValid = false; 
    } 

    if (isValid == false) 
    { 
     MessageBox.Show(strErrors); 
    } 

    return isValid; 
} 
+0

一个StringBuilder一般会表现得更好,但这里这么弦数并不那么重要。 –