验证输入多个文本框

时间:2016-09-26 15:16:53

标签: c#

我正在使用此方法在另一个方法中读取数据和设置字段,是否可以验证每个字段是否为空或包含除数字以外的其他方法?

我希望能够显示一个消息框“填写所有文本框”目前,如果我为每个文本框添加一个else方法(最坏的情况是4个消息框)..

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

1 个答案:

答案 0 :(得分:2)

这样的事情可能是:

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