我的代码每3秒钟增加1到100分钟。它显示10102103104105.我想要的是101消失而102代替那里等等
int i = 100;
private void timer5_Tick(object sender, EventArgs e)
{
i++;
textBox2.Text += i.ToString();
}
答案 0 :(得分:4)
这是你的问题:
textbox2.Text += i.ToString();
这是写这个的简写方式:
textbox2.Text = textbox2.Text + i.ToString();
因此,如果您的文本框已包含100
,那么您所说的是:
textbox2.Text = "100" + i.ToString(); // The textbox now contains "100101"
在下一次迭代中,它看起来像这样:
textbox2.Text = "100101" + i.ToString(); // the textbox now contains "100101102"
等等....所以改变这一行:
textbox2.Text = i.ToString();
因此,如果您的文本框包含100
,则会在下一次迭代中发生这种情况:
textbox2.Text = i.ToString(); // the textbox now contains "101"
等等......
=
运算符表示Assign the value on the right hand side of the equal sign to the variable on the left hand side
。
+=
运算符表示Append the value on the right hand side of the equal sign to the contents of the variable on the left hand side
。
看到那里的差异? Assign
与Append
答案 1 :(得分:3)
您在方法中附加i
的值。您只需要指定值。
int i = 100;
private void timer5_Tick(object sender, EventArgs e) {
i++;
textBox2.Text = i.ToString(); // ASSIGN HERE!
}
答案 2 :(得分:1)
您应该将值分配给文本框,而不是附加它。
textBox2.Text = i.ToString();