在表格上显示时钟 [英] Display clock on Form
本文介绍了在表格上显示时钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Windows窗体的面板中显示时钟(每秒更新的数字时钟)。我写下面的代码。
I want to display clock (digital clock which update in every second) in panel on windows form. I write following code.
Panel agentPanel;
Label lblTime;
Timer timer1;
private void CreateAgentPanels(int numberofPanel, string Current_Status, string Op_id)
{
for(int i =0; i <= numberofPanel;i++)
{
agentPanel = new Panel();
lblTime = new Label();
lblTime.Location = new Point(02, 35);
lblTime.AutoSize = true;
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
this.timer1.Interval = 1000;
timer1.Start()
agentPanel.Controls.Add(lblTime);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString(HH:mm:ss);
}
但lblTime标签仅显示在最后一个循环面板中。如何在循环中创建的每个面板中显示。
先谢谢
but lblTime label displays only in the last panel of loop. how to display in every panel which created in the loop.
Thanks in Advance
推荐答案
尝试一下像这样:
Try something like this:
List<Label> listOfLabels = new List<Label>();
private void CreateAgentPanels(int numberofPanel, string Current_Status, string Op_id)
{
Panel agentPanel;
Label lblTime;
for(int i =0; i <= numberofPanel;i++)
{
agentPanel = new Panel();
agentPanel.BackColor = Color.Blue;
agentPanel.AutoSize = true;
agentPanel.Size = new Size(50, 50);
agentPanel.Location = new Point((i * 52), 0);
lblTime = new Label();
lblTime.Location = new Point(02, 35);
lblTime.AutoSize = true;
listOfLabels.Add(lblTime);
agentPanel.Controls.Add(lblTime);
this.Controls.Add(agentPanel);
}
Timer timer1;
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach (Label l in listOfLabels)
{
l.Text = DateTime.Now.ToString("HH:mm:ss");
}
}
在表单级别创建一个List,将lblTime添加到CreateAgentPanels中的列表,然后再添加到timer1_Tick方法中,遍历此列表并设置文本。
Create a List at the Form level, add the lblTime to the list in CreateAgentPanels and then in the timer1_Tick method, loop through this list and set it's text.
这篇关于在表格上显示时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文