Ron Reyes
Ron Reyes

Reputation: 35

Displaying multiple error messages in a single message box

I'm currently developing a desktop application with a product maintenance page and im looking for a way to display all validation errors in a single message box.

I am displaying one message box per validation error by using the code below: (validations are bound to a save button)

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

I'd like to give the users the ease of knowing all the errors at once as opposed to knowing them one by one per message box shown.

thanks in advance! :)

Upvotes: 2

Views: 3140

Answers (2)

Eslam Hamouda
Eslam Hamouda

Reputation: 1151

a quick dirty solution will be :

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

Upvotes: 0

M.Azad
M.Azad

Reputation: 3763

you can use StringBuilder and add Errors in it :

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

Upvotes: 2

Related Questions