How to add a timer to a dynamic created labels in a winform C#?

余生颓废 提交于 2021-01-29 14:41:44

问题


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");
    }
...
}

回答1:


You can use this:

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;
}


来源:https://stackoverflow.com/questions/58167811/how-to-add-a-timer-to-a-dynamic-created-labels-in-a-winform-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!