Search code examples
c#int32

Getting wrong answer when int32 behave wierd, how do I solve it? C#


Im trying to get the result with this code. It is suppose to work with whatever numer/numbers I choose, but it does only work with a "0" in the end. (val1, is the textbox I am writing the number/numbers in) and (yarncombobox, ft3.garnlangd1 is where I get the value that is needed in the calculation). I guess Int32 might be wrong...what should I use instead?

Also, When removing all numbers I get error message "System.FormatException: 'Indatasträngen hade ett felaktigt format.'"

private void YarnWeightTextbox_TextChanged(object sender, EventArgs e)

            Int32 val1 = Convert.ToInt32(YarnWeightTextbox.Text);
        Class2 ft3 = YarnComboBox.SelectedItem as Class2;
        {
            YarnLengthTextbox.Text = Convert.ToString((val1 / 50) * ft3.garnlangd1);

Edit: I did get it somewhat to work, it does give right value with float. But the same problem. When deleting all numbers in the same box the app crashes.

            float val1 = Convert.ToSingle(YarnWeightTextbox.Text);
        Class2 ft3 = YarnComboBox.SelectedItem as Class2;
        float val2 = val1 / 50 * ft3.garnlangd1;
        {
            YarnLengthTextbox.Text = Convert.ToString(val2);

Solution

  • As Shane Haw mentioned in the comments, you're getting the FormatException because the TextChanged event fires any time the text changes.

    If the value in YarnWeightTextBox.Text is "5", and you delete the "5" then the TextChanged event fires. Which means that you are passing an empty string "" to Convert.ToSingle. An empty string does not convert to a float and so you get the FormatException. You will get the same thing if you put anything other than a digit in that TextBox as well.

    A better option would be to check if the value in YarnWeightTextBox.Text parses to a float instead of using Convert.ToFloat.

    private void YarnWeightTextBox_TextChanged(object sender, EventArgs e)
    {
       float val1 = 0.0F;
       if (!float.TryParse(YarnWeightTextBox.Text, out val1))
       {
          // The value in YarnWeightTextBox.Text does not parse to a float. You could 
          // do something here to indicate to the user that they did not provide a correct
          // value, or just return.
          return;
       }
       // Calculate the yarn length and put it in the YarnLengthTextBox.Text like you're doing now.
    }
    

    Alternatively, if this is Windows Forms, you might have a look at the NumericUpDown control which will prevent users for entering invalid values.