Float. Tryparse Not Working

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

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

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.

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.