1

I'm reading data and setting fields in another method with this method, is it possible to validate that each field is not empty or contains other than numbers?

I wanna be able to display one messagebox "Fill in all textboxes" Currently if I add an elsemethod for each I get (in worst case 4 messageboxes)..

    private bool ReadInput()
    {
        double curReading = 0;
        double prevReading = 0;
        double amount = 0;
        double unitNumber = 0;

        if (double.TryParse(tbReading.Text, out curReading))
        {
            CalcData.SetCurrentReading(curReading);
        }

        if (double.TryParse(tbPrevReading.Text, out prevReading))
        {
            CalcData.SetPrevReading(prevReading);
        }

        if (double.TryParse(tbAmount.Text, out amount))
        {
            CalcData.SetAmount(amount);
        }

        if (double.TryParse(tbUnitNumber.Text, out unitNumber))
        {
            CalcData.SetUnitNumber(unitNumber);
        }
        return false;
    }
noxious
  • 57
  • 2
  • 11
  • Take a look at: [Validation using Validating event and ErrorProvider - Show Error Summary](http://stackoverflow.com/a/33080822/3110834) – Reza Aghaei Sep 26 '16 at 19:01
  • Also to know more options about windows forms validation, take a look at this post: [Validating user input / Give .NET controls status OK or NOK](http://stackoverflow.com/a/35993185/3110834) – Reza Aghaei Sep 26 '16 at 19:03

1 Answers1

2

Something like this maybe:

private bool ReadInput()
{
    double curReading = 0;
    double prevReading = 0;
    double amount = 0;
    double unitNumber = 0;
    var validData = true;

    if (double.TryParse(tbReading.Text, out curReading))
    {
        CalcData.SetCurrentReading(curReading);
    }
    else
    {
        validData = false;
    }

    if (double.TryParse(tbPrevReading.Text, out prevReading))
    {
        CalcData.SetPrevReading(prevReading);
    }
    else
    {
        validData = false;
    }

    if (double.TryParse(tbAmount.Text, out amount))
    {
        CalcData.SetAmount(amount);
    }
    else
    {
        validData = false;
    }

    if (double.TryParse(tbUnitNumber.Text, out unitNumber))
    {
        CalcData.SetUnitNumber(unitNumber);
    }
    else
    {
        validData = false;
    }

    if(!validData)
    {
        //Show your dialog here
    }

    return false;
}
Kevin
  • 1,462
  • 9
  • 9