我想要输入不同间隔的不同计时器。例如,如果我输入 4,则 4 个计时器创建并在 4 个标签中显示时间,其中第一个计时器的时间在 1 秒内变化,第二个计时器的时间在 2 秒内变化,第三个计时器的时间在 3 秒内变化4tn 计时器的时间在 4 秒内变化。这是我的代码,
string input = textBox2.Text;
int n = Convert.ToInt32(input);
for (i = 1; i <= n; i++)
{
Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = (1000) * (i);
timer.Enabled = true;
timer.Start();
Label label = new Label();
label.Name = "label"+i;
label.Location = new Point(100, 100 + i * 30);
label.TabIndex = i;
label.Visible = true;
this.Controls.Add(label);
}
private void timer_Tick(object sender, EventArgs e)
{
label.Text = DateTime.Now.ToString();
}
但我没有得到任何输出。我能做什么。我使用 Windows 应用程序。
我不明白计时器的 Tick 事件处理程序如何访问不在其范围内的动态标签。
Try
Label label = new Label();
label.Name = "label"+i;
label.Location = new Point(100, 100 + i * 30);
label.TabIndex = i;
label.Visible = true;
Timer timer = new Timer();
timer.Tick += (s, e) => label.Text = DateTime.Now.ToString();
timer.Interval = (1000) * (i);
timer.Enabled = true;
timer.Start();
另一种选择是有一个Dictionary<Timer, Label>
并在创建控件时将控件添加到该字典中,并在计时器的滴答处理程序中使用字典来检索其相应的Label
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)