首页 > 解决方案 > C# 如何将错误附加到 1 个单个消息框中?

问题描述

这是我在 C# 中的当前代码:

if (string.IsNullOrEmpty(textBox1.Text))
{
    MessageBox.Show("User Field Is Empty");
    return;
}

if (string.IsNullOrEmpty(textBox2.Text))
{
    MessageBox.Show("Document Reference Code Field Is Empty");
    return;
}

什么是创建数组并附加到数组以显示 1 个 MessageBox 并指出空值的正确方法,而不是拥有多个 MessageBox 并为每个错误消息单击“确定”?

我正在尝试复制它与此 Python 代码相同:

errors = []
if self.nameEntry.get() == '':
     errors.append('User')
if self.documentReferenceCodeEntry.get() == '':
    errors.append('Document Reference')
        if errors:
            messagebox.showerror("Error", "Following fields are empty:" +'\n' + '\n'.join(errors))
            return('error')

上面的代码是什么,如果该字段为空,则将其附加到errors数组中,最后将所有错误显示到 1 个消息框中。

这是 Python 代码的输出:

在此处输入图像描述

标签: c#python

解决方案


使用 List 存储错误,如果列表不为空,则显示 MessageBox

List<string> errors = new List<string>();
if (string.IsNullOrEmpty(textBox1.Text))
{
    errors.Add("User");
}

if (string.IsNullOrEmpty(textBox2.Text))
{
    errors.Add("Document Reference Code");
}

if(errors.Count > 0)
{
    errors.Insert(0, "The following fields are empty:");
    string message = string.Join(Environment.NewLine, errors);
    MessageBox.Show(message);
}

推荐阅读