Click here to Skip to main content
15,895,462 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a small app that creates dynamically a panels that include ( table layout panel where there is a list box and a label in this table) the question is how i m gonna assign a timer in that label for every panel created? and also how i m gonna start the timer from 00:00? here is the code:

C#
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");

        }


What I have tried:

i have tried this code but only adds the timer to the last label in the last panel created.
Posted
Updated 1-Oct-19 4:50am
v2
Comments
ZurdoDev 30-Sep-19 8:12am    
Same way you are creating dynamic labels, create dynamic timers.

1 solution

The way I'd do it is to create a single timer, and add your labels to a collection that it can examine.
When your single timer gets a Tick event, it checks the collection for each label instead of needing a a separate timer for each one. If the label needs specific timeout period, set the end time into the Label.Tag property as a DateTime, and compare it to DateTime.Now in the Tick handler.
That way, you can write a method which processes a tick for a single label, and call it repeatedly from the single Tick event passing the Label through as a parameter.
 
Share this answer
 
Comments
Maciej Los 2-Oct-19 4:21am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900