如何在Winform C#中为动态创建的标签添加计时器?

问题描述 投票:0回答:1

我有一个小应用程序,可以动态创建一个面板,该面板包括一个表格布局面板,其中有一个列表框和一个标签。问题是我如何在动态创建的每个标签中分配一个计时器,以及如何从00:00开始计时器?我已经尝试过此代码,但只将计时器添加到创建的最后一个面板的最后一个标签中:

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");
    }
...
}
c# timer label
1个回答
0
投票

您可以使用此:

private List<Timer> Timers = new List<Timer>();

public Form1()
{
  InitializeComponent();
  var p = new Panel();
  p.Size = new Size(360, 500);
  p.BorderStyle = BorderStyle.FixedSingle;
  p.Name = "panel";
  var tpanel = new TableLayoutPanel();
  tpanel.Name = "tablepanel";
  ListBox lb = new ListBox();
  tpanel.Controls.Add(lb = new ListBox() { Text = "qtylistBox2" }, 1, 3);

  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.ToString("mm\\:ss"); };
    Timers.Add(timer);
    timer.Enabled = true;
  };

  // create one label
  createLabel("0", 2, 1);

  // create other label
  // createLabel("", 0, 0);
}

备选:

private List<Timer> Timers = new List<Timer>();

public Form1()
{
  InitializeComponent();
  var p = new Panel();
  p.Size = new Size(360, 500);
  p.BorderStyle = BorderStyle.FixedSingle;
  p.Name = "panel";
  var tpanel = new TableLayoutPanel();
  tpanel.Name = "tablepanel";
  ListBox lb = new ListBox();
  tpanel.Controls.Add(lb = new ListBox() { Text = "qtylistBox2" }, 1, 3);

  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.ToString("mm\\:ss"); };
    Timers.Add(timer);
  };

  // create one label
  createLabel("0", 2, 1);

  // create other label
  // createLabel("", 0, 0);

  foreach ( var timer in Timers )
    timer.Enabled = true;
}
© www.soinside.com 2019 - 2024. All rights reserved.