float.TryParse not working

I created program that calculates the currency exchange rate. The program has:

  1. ComboboxCurrencyName - which displays the currency name.
  2. ComboCurrencyValue - which displays the value of a given currency.
  3. txtYourValue - textbox which gets from user the amount of money
  4. 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.

Breakpoint

Application window

8

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like