[英]How to add a timer to a dynamic created labels in a winform C#?
我有一个小应用程序,它动态创建一个面板,其中包括一个表格布局面板,其中有一个列表框和一个 label。 问题是我将如何在每个动态创建的 label 中分配一个计时器,以及我将如何从 00:00 开始计时器? 我已经尝试过这段代码,但只将计时器添加到最后一个创建的面板中的最后一个 label:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.