Reputation: 67
I want different timer with different interval that i input.For example, if I input 4, 4 timer create and show time in 4 label, where 1st timer's time change in 1sec,2nd timer's time change in 2sec,3rd timer's time change in 3sec and 4tn timer's time change in 4sec.Here is my code,
string input = textBox2.Text;
int n = Convert.ToInt32(input);
for (i = 1; i <= n; i++)
{
Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = (1000) * (i);
timer.Enabled = true;
timer.Start();
Label label = new Label();
label.Name = "label"+i;
label.Location = new Point(100, 100 + i * 30);
label.TabIndex = i;
label.Visible = true;
this.Controls.Add(label);
}
private void timer_Tick(object sender, EventArgs e)
{
label.Text = DateTime.Now.ToString();
}
But i don't get any output.What can i do.I use windows application.
Upvotes: 2
Views: 10756
Reputation: 2566
The other way, than Bala R shown to you is keep reference of variable in a dictionary (dict) for timer and label pairs, and access in event handler by sender reference (Full source code, with 2 text boxes ans a button, 2nd textbox contains text "3"), hope it will help:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ProjectDocumentationWorkspace.UI
{
public partial class MainForm : Form
{
private Dictionary<Timer, Label> dict = new Dictionary<Timer, Label>();
public MainForm()
{
InitializeComponent();
}
private void CreateTimers()
{
string input = textBox2.Text;
int n = Convert.ToInt32(input);
for (int i = 1; i <= n; i++)
{
Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = (1000) * (i);
Label label = new Label();
label.Name = "label" + i;
label.Location = new Point(100, 100 + i * 30);
label.TabIndex = i;
label.Visible = true;
this.Controls.Add(label);
dict[timer] = label;
timer.Enabled = true;
timer.Start();
}
}
private void timer_Tick(object sender, EventArgs e)
{
Timer t = (Timer)sender;
DateTime current = DateTime.Now;
dict[t].Text = string.Format("{0:00}:{1:00}:{2:00}", current.Hour, current.Minute, current.Second);
}
private void button1_Click(object sender, EventArgs e)
{
CreateTimers();
}
}
}
Upvotes: 1
Reputation: 109037
I don't see how the Timer's Tick event handler can access a dynamic label that's not in it's scope.
Try
Label label = new Label();
label.Name = "label"+i;
label.Location = new Point(100, 100 + i * 30);
label.TabIndex = i;
label.Visible = true;
Timer timer = new Timer();
timer.Tick += (s, e) => label.Text = DateTime.Now.ToString();
timer.Interval = (1000) * (i);
timer.Enabled = true;
timer.Start();
Another alternative is to have a Dictionary<Timer, Label>
and add controls to this dictionary as they are created and in the timer's tick handler use the dictionary to retrieve its corresponding Label
Upvotes: 2