如何实施负值验证

时间:2015-04-25 02:22:55

标签: c# validation

我正在处理此代码段

  private void calculateButton_Click(object sender, EventArgs e)
    {
        int amount;
        if (int.TryParse(amountTextBox.Text, out amount))
        {
            wantedTextBox.Text = Currency_Exchange.exchangeCurrency((Currencies)currencyComboBox.SelectedIndex, (Currencies)wantedCurrencyComboBox.SelectedIndex, amount).ToString("0.00");                
            wantedCurrencyLable.Text = ((Currencies)wantedCurrencyComboBox.SelectedIndex).ToString();
        }

        else {
            MessageBox.Show("Invalid amount");
        }


    }

并且意识到太迟了,我应该对负数进行验证。但是我设置代码的方式使得这有点困难。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

存储TryParse结果的值,然后检查同一amount语句中的if,如下所示:

boolean parseResult = int.TryParse(amountTextBox.Text, out amount)

if (parseResult && amount >= 0)
{
    //....
}
else
{
    MessageBox.Show("Invalid amount");
}