5

我还是 C# 的新手,想知道当满足 if 条件时如何会发生多种事情。例如。

int number = (Convert.ToInt32(textbox1.text)); 
   if (number == 1)
         textbox2.Text = "1";                 
         number2 = 33;           
         textbox3.text = (Convert.ToString(number2));

当我做这样的事情时,它并没有完成所有想要的结果。

PS如果这不是解决此类新手问题的正确网站,有人知道我可以去哪里吗?(当然经过研究)。

4

7 回答 7

7
if (number == 1) 
{
    textbox2.Text = "1";                 
    number2 = 33;           
    textbox3.text = (Convert.ToString(RSP));
}

添加括号将语句组合在一起。

如果没有括号,if 语句只会影响下一个语句:textbox2.Text = "1";,并且其他语句将始终运行,而不管 if 语句。

于 2012-07-14T20:37:40.757 回答
2

您需要使用块,使用{}字符...

int number = (Convert.ToInt32(textbox1.text)); 
if (number == 1)
{
    textbox2.Text = "1";                 
    number2 = 33;           
    textbox3.text = (Convert.ToString(RSP));
}
于 2012-07-14T20:38:02.640 回答
2

您需要将其全部包裹在花括号 { }

int number = Convert.ToInt32(textbox1.text); 
if (number == 1)
{
   textbox2.Text = "1";                 
   number2 = 33;           
   textbox3.text = Convert.ToString(RSP);
}

Also the parenthesis around your Convert functions are not necessary. Doesn't affect functionality, just general house keeping.

于 2012-07-14T20:38:05.963 回答
2

If the statements under the if statement is more than 1, braces are required.

   int number = (Convert.ToInt32(textbox1.text));  
   if (number == 1) 
   {
         textbox2.Text = "1";                  
         number2 = 33;            
         textbox3.text = (Convert.ToString(RSP)); 
   }
于 2012-07-14T20:38:17.617 回答
1
int number = (Convert.ToInt32(textbox1.text)); 
if (number == 1)
 {
     textbox2.Text = "1";                 
     number2 = 33;           
     textbox3.text = (Convert.ToString(RSP));
 }

使用大括号。这显示了要在 IF 语句上执行的代码块

于 2012-07-14T20:37:47.283 回答
1

Wrap the block of code in curly braces ({}).

int number = (Convert.ToInt32(textbox1.text)); 
if (number == 1)
{
    textbox2.Text = "1";
    number2 = 33;
    textbox3.text = (Convert.ToString(number2));
 }
于 2012-07-14T20:38:40.243 回答
0

You missed the scope {}

int number = (Convert.ToInt32(textbox1.text));
if (number == 1)
{
     textbox2.Text = "1";
     number2 = 33;
     textbox3.text = (Convert.ToString(number2));
}

OR

int number = int.Parse(textbox1.text);
if (number == 1)
{
     textbox2.Text = "1";
     number2 = 33;
     textbox3.text = number2.ToString();
     //the above line can also be written as follows
     //textbox3.text = "" + number2;
}

Both will work fine

于 2012-07-15T05:42:55.653 回答