Ron Reyes Ron Reyes - 2 months ago 14
C# Question

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! :)

Answer

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