Reputation: 33
I was working on this code snippet
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");
}
}
and realized way too late that I should put in validation for negative numbers. But the way i've set up the code makes that slightly difficult. How could I do this?
Upvotes: 0
Views: 888
Reputation:
Store the value of TryParse
result, then check the amount
in the same if
statement, like so:
boolean parseResult = int.TryParse(amountTextBox.Text, out amount)
if (parseResult && amount >= 0)
{
//....
}
else
{
MessageBox.Show("Invalid amount");
}
Upvotes: 2