在MessageBox show方法中显示错误列表

本文关键字:显示 错误 列表 方法 MessageBox show | 更新日期: 2023-09-27 18:04:30

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

    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;
    }

但是,您不能在Show方法中使用String类型的List。什么好主意吗?

在MessageBox show方法中显示错误列表

您可以使用以下命令:

        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);

为什么不使用字符串呢?

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;
}