Ulcis Ulcis - 1 month ago 15
C# Question

Validating multiple fields

I used Visual Studio to create an application that features 3 fields where 3 numbers can be added together. Now, I need to validate all 3 fields so that negative numbers cannot be added. If a negative number is entered, each field has also to return a unique message like: "please enter a positive first number."

I figured out how to do that for one field, but how do I set it up for all 3 fields to not accept negative numbers (and display a unique message)?

Here is what I have:

{
int num = int.Parse(txtNum1.Text);

if (num <0)
{
MessageBox.Show("Please enter a positive first number");
}
else
{
int num1 = int.Parse(txtNum1.Text);
int num2 = int.Parse(txtNum2.Text);
int num3 = int.Parse(txtNum3.Text);
int sum = num1 + num2 + num3;
txtResult.Text = sum.ToString();
}


Hopefully this makes sense.

Answer

This might help you

int num = 0;
bool atLeastOneisNegative = false;
foreach (Control x in this.Controls)
{
    if (x is TextBox)
    {
        num = 0;
        num = int.Parse(((TextBox)x).Text);
        if(num < 0)
        {
            atLeastOneisNegative = true;
            MessageBox.Show("Please enter a positive first number");
        }
    }
}   

if(!atLeastOneisNegative)
{
    int num1 = int.Parse(txtNum1.Text);
    int num2 = int.Parse(txtNum2.Text);
    int num3 = int.Parse(txtNum3.Text);
    int sum = num1 + num2 + num3;
    txtResult.Text = sum.ToString();
}

Whereas the question is not stating whether you are using WPF or WinForms. But the logic might help you to achieve to iterate all your TextBoxes and see the value is Positive.