反转循环

mrN*_*ame 0 c# loops

我做了这个小嵌套for循环,并且它在C#中没有显示任何错误,但是当我尝试运行我的小程序时,我得到以下错误TextBox:

System.Windows.Forms.TextBox,Text:System.Windows.Forms.TextBox,Text:Syst ...

这是我的代码:

int number = textBox.Text..ToString();
for (int row = 0; row < number; row++)
{
    for (int x = number - row; x > 0; x--)
    {
        textBox2.Text = textBox2.Text + "X";
    }
    textBox2.Text = textBox2 + Environment.NewLine;
}
Run Code Online (Sandbox Code Playgroud)

我的结果应该是这样的:


XXXX
XXX
XX
X.

我无法弄清楚可能导致此错误的原因.

Ree*_*sey 6

您不能将字符串分配给数字.你需要转换它:

// int number = textBox.Text..ToString();
int number;
if (!int.TryParse(textBox.Text, out number)
{
    // Handle improper input...
}

// Use number now
Run Code Online (Sandbox Code Playgroud)

此外,当您添加换行符时,您需要实际附加到Text属性,而不是TextBox本身:

textBox2.Text = textBox2.Text + Environment.NewLine;
Run Code Online (Sandbox Code Playgroud)


Gol*_*den 5

代替

textBox2.Text = textBox2 + 
Run Code Online (Sandbox Code Playgroud)

使用

textBox2.Text = textBox2.Text + 
Run Code Online (Sandbox Code Playgroud)

在最后一行.

而已 ;-)

  • 这只是多个问题中的一个......修复该行仍然不允许代码编译. (4认同)