Showing a list of errors in MessageBox show method
I'm trying to figure out a way to show a listing of validation errors in my app using MessageBox.Show. So fa开发者_JS百科r I have this:
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;
}
But alas, you cannot use a List of type String inside the Show method. Any ideas?
You could use the following:
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);
Why not use a string?
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;
}
精彩评论