我有这个小代码片段,我一直在努力。它的作用是为超过2位小数的数字提供验证。
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();
groupBox.Visible = true;
}
else {
MessageBox.Show("Invalid amount");
}
现在我已经意识到我已经太晚了,我也应该对负数进行验证。然而,我设置代码的方式使得这很困难。有人建议我将文本框的解析声明为布尔值,但这只会造成更多麻烦。我怎么能这样做?
答案 0 :(得分:1)
如果TryParse
成功,则解析后的值将存储在amount
中,因此请先使用此值确保其有效号码然后,如果它是,该数量大于或等于0:
if (int.TryParse(amountTextBox.Text, out amount) && amount >= 0)