kdad
kdad

Reputation: 45

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

Upvotes: 3

Views: 20766

Answers (1)

Yair Halberstadt
Yair Halberstadt

Reputation: 6851

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.

Upvotes: 10

Related Questions