Error when trying to get an int from textbox

前端 未结 5 1068
时光取名叫无心
时光取名叫无心 2021-01-20 04:37

I am new to C# and programming in general. I was able to create the required program in Console but want to get one working with Forms as well. I am running into an issue wh

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-20 04:53

    Why do you name your ints like your textboxes? It is really a bad practice and confusing at the uttermost level. As you can see, the compiler thinks that you are using the int variables instead of the textboxes and complains that an int type have no property called Text.

    So simply change the name of the ints inside the click method

       private void button1_Click(object sender, EventArgs e)
       {
            int l;
            int w;
            int h;
            int paint;
            int answer;
    
            l = int.Parse(LengthtextBox.Text);
            w = int.Parse(WidthtextBox.Text);
            h = int.Parse(HeighttextBox.Text);
            paint = 350;
    
            answer = (l * w * h) / paint;
    
             MessageBox.Show( answer.ToString() );
        }
    

    Said that, I suggest to use Int32.TryParse to convert the data typed by your user in a valid integer. The Parse method will throw an exception if your user types something that cannot be translated to an integer, instead TryParse returns false without a costly exception

    For example

      int l;
      if(!Int32.TryParse(LengthtextBox.Text, out l))
      {
           MessageBox.Show("Please type a valid number for Length");
           return;
      }
    

    When the Int32.TryParse returns, the out parameter (l) contains the 32-bit signed integer value equivalent of the number contained in your textbox, if the conversion succeeds, or zero if the conversion fails

提交回复
热议问题