I created program that calculates the currency exchange rate. The program has:
- ComboboxCurrencyName - which displays the currency name.
- ComboCurrencyValue - which displays the value of a given currency.
- txtYourValue - textbox which gets from user the amount of money
- Button that calculates the rate of the given currency with the amount of money given from user.
My code:
public void EchangeRate(float x,float y)
{ label1.Text = (x * y).ToString();
}
private void button1_Click(object sender, EventArgs e)
{ if(comboCurrencyName.SelectedIndex==comboCurrencyValue.SelectedIndex) { float currency; float inputValue; if(float.TryParse(comboCurrencyValue.SelectedItem.ToString(),out currency)&& float.TryParse(txtYourValue.Text,out inputValue)) { EchangeRate(currency,inputValue); } } else { MessageBox.Show("Not selected currency "); }
}When I select a given currency with a combobox and I'm entering the value to convert, nothing happens when I press the button. I think this is a problem with converting combobox to float value.
Previously I used float.Parse() I had the error:
System.FormatException: 'Invalid input string format.
1 Answer
Replace with:
(float.TryParse(comboCurrencyValue.SelectedItem.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture,out currency)&& float.TryParse(txtYourValue.Text,out inputValue)) To explain: in Poland a comma is used instead of a decimal point, so you must specify that you want to use an invariant culture.
6