Noxious Noxious - 2 months ago 21
C# Question

Validate input multiple textboxes

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

Answer

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