如何在Winform C#中为动态创建的标签添加计时器? [英] How to add a timer to a dynamic created labels in a winform C#?
本文介绍了如何在Winform C#中为动态创建的标签添加计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个小型应用程序,可以动态创建一个面板,该面板包括一个表格布局面板,其中有一个列表框和一个标签.问题是如何在动态创建的每个标签中分配一个计时器,以及如何从00:00开始计时器?我已经尝试过此代码,但只将计时器添加到创建的最后一个面板中的最后一个标签中:
I have a small app that creates dynamically a panel that includes a table layout panel where there is a list box and a label. The question is how I'm gonna assign a timer in every label created dynamically and also how I'm gonna start the timer from 00:00? I have tried this code but only adds the timer to the last label in the last panel created:
public Form1() {
InitializeComponent();
p = new Panel();
p.Size = new System.Drawing.Size(360, 500);
p.BorderStyle = BorderStyle.FixedSingle;
p.Name = "panel";
tpanel = new TableLayoutPanel();
tpanel.Name = "tablepanel";
ListBox lb = new ListBox();
tpanel.Controls.Add(lb = new ListBox() {
Text = "qtylistBox2"
}, 1, 3);
Label l6 = new Label();
tpanel.Controls.Add(l6 = new Label() {
Text = "0"
}, 2, 1)
//here is the timer that i created
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Enabled = true;
public void timer1_Tick(object sender, EventArgs e) {
l6.Text = DateTime.Now.ToString("mm\\:ss");
}
...
}
推荐答案
您可以使用此
private Dictionary<Timer, DateTime> Timers = new Dictionary<Timer, DateTime>();
public Form1()
{
InitializeComponent();
var p = new Panel();
p.Size = new Size(360, 500);
p.BorderStyle = BorderStyle.FixedSingle;
p.Name = "panel";
Controls.Add(p);
var tpanel = new TableLayoutPanel();
tpanel.Name = "tablepanel";
tpanel.Controls.Add(new ListBox() { Text = "qtylistBox2" }, 1, 3);
p.Controls.Add(tpanel);
Action<string, int, int> createLabel = (text, x, y) =>
{
var label = new Label();
label.Text = text;
tpanel.Controls.Add(label, x, y);
var timer = new Timer();
timer.Interval = 1000;
timer.Tick += (sender, e) =>
{
label.Text = DateTime.Now.Subtract(Timers[sender as Timer]).ToString("mm\\:ss");
};
Timers.Add(timer, DateTime.Now);
};
// create one label
createLabel("0", 2, 1);
// create other label
// createLabel("", 0, 0);
foreach ( var item in Timers )
item.Key.Enabled = true;
}
这篇关于如何在Winform C#中为动态创建的标签添加计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文