Как добавить таймер к динамически создаваемым меткам в winform C #? - PullRequest
0 голосов
/ 30 сентября 2019

У меня есть небольшое приложение, которое динамически создает панель, которая включает панель макета таблицы, в которой есть поле со списком и метка. Вопрос в том, как назначить таймер для каждого динамически создаваемого ярлыка, а также как запустить таймер с 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");
    }
...
}

1 Ответ

0 голосов
/ 30 сентября 2019

Вы можете использовать это:

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