简体   繁体   中英

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);

Here are a couple of suggestions:

private void YarnWeightTextbox_TextChanged(object sender, EventArgs e)
{
        //Check for the empty string. If it is empty then just return
        string weight = YarnWeightTextbox.Text;
        if(String.IsNullOrEmpty(weight))
        {
            return;
        }

        //Otherwise convert to integer or to a float as you have
        Int32 val1 = Convert.ToInt32(YarnWeightTextbox.Text);

        Class2 ft3 = YarnComboBox.SelectedItem as Class2;
        //When casting using the `as` operator. I make a point of checking for null just
        //in case for some reason it isn't an instance of the class I expect.
        if(ft3 != null)
        {
            //Finally change the 50 to 50.0. This tells the compiler to divide using a float
            //rather than an integer. Dividing 2 integers results in the truncation of the fractional part
            YarnLengthTextbox.Text = Convert.ToString((val1 / 50.0) * ft3.garnlangd1);
        }
}

The most important parts are:

  1. Check for empty string
  2. Divide using float division rather than integer division as integer division will remove the fractional part of the result, which may account for some of the strange results that you are seeing.
private void YarnWeightTextbox_TextChanged(object sender, EventArgs e)
{
    if (sender is TextBox textBox)
    {
        if (float.TryParse(textBox.Text, out var yarnWeight) && YarnComboBox.SelectedItem is Class2 class2)
        {
            var yarnLength = (yarnWeight / 50.0) * class2.garnlangd1;

            YarnLengthTextbox.Text = yarnLength.ToString();
        }
        else
        {
            YarnLengthTextbox.Text = string.Empty;
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM