【问题标题】:Displaying multiple error messages in a single message box在单个消息框中显示多条错误消息
【发布时间】:2016-09-10 18:38:20
【问题描述】:

我目前正在开发一个带有产品维护页面的桌面应用程序,我正在寻找一种在单个消息框中显示所有验证错误的方法。

我使用下面的代码为每个验证错误显示一个消息框:(验证绑定到保存按钮)

        if ((Convert.ToInt32(txtQuantity.Text)) > 20000)
        {
            MessageBox.Show("Maximum quantity is 20,000!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            txtQuantity.Focus();
            return;
        }

        if ((Convert.ToInt32(txtQuantity.Text)) <= (Convert.ToInt32(txtCriticalLevel.Text)))
        {
            MessageBox.Show("Quantity is lower than Critical Level.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            txtQuantity.Focus();
            return;
        }

        if (txtCriticalLevel.Text == "0")
        {
            MessageBox.Show("Please check for zero values!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            txtCriticalLevel.Focus();
            return;
        }

我想让用户轻松地一次了解所有错误,而不是每个显示的消息框一一了解。

提前致谢! :)

【问题讨论】:

    标签: c# validation messagebox


    【解决方案1】:

    您可以使用 StringBuilder 并在其中添加错误:

    StringBuilder sb = new StringBuilder();
    
    
     if ((Convert.ToInt32(txtQuantity.Text)) > 20000)
            {
                  sb.AppendLine("Maximum quantity is 20,000!");            
            }
    
    
    
    if ((Convert.ToInt32(txtQuantity.Text)) <= (Convert.ToInt32(txtCriticalLevel.Text)))
        {
           sb.AppendLine("Quantity is lower than Critical Level.");
        }
    
    ....
      MessageBox.Show(sb.ToString(), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    

    【讨论】:

    • 感谢您的回答!我会调查这个,但我将如何考虑验证?你能给我看一个可能的样本吗? :)
    • @RonReyes 我更新我的答案 ;)
    【解决方案2】:

    一个快速的肮脏解决方案是:

        string errorMessages = String.Empty;
    
        if ((Convert.ToInt32(txtQuantity.Text)) > 20000)
        {
            errorMessages +="- Maximum quantity is 20,000!\r\n";
            txtQuantity.Focus();
            return;
        }
    
        if ((Convert.ToInt32(txtQuantity.Text)) <= (Convert.ToInt32(txtCriticalLevel.Text)))
        {
            errorMessages += "- Quantity is lower than Critical Level.\r\n";
            txtQuantity.Focus();
            return;
        }
    
        if (txtCriticalLevel.Text == "0")
        {
            errorMessages += "- Please check for zero values!\r\n";
            txtCriticalLevel.Focus();
            return;
        }
    
        if(!String.IsNullOrEmpty(errorMessages))
            MessageBox.Show(errorMessages, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    

    【讨论】:

    • 当你连接字符串时最好使用 StringBuilder msdn.microsoft.com/en-us/library/ms228504.aspx
    • 你的代码创造了奇迹!!!太感谢了!!但你能解释一下为什么它“脏”吗?
    • 因为它需要一些重构才能使用'StringBuilder'而不是像@M.Azad所说的字符串连接,并且可能是一些字符串格式。
    猜你喜欢
    • 2020-12-20
    • 1970-01-01
    • 2017-04-26
    • 2011-02-03
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    相关资源
    最近更新 更多