我正在尝试使用C#创建一个小程序,告诉我下一个地铁到期的时间。到目前为止我已对此进行了编码,但是当我更改系统时间时,Next Metro标签不会更改。任何想法出了什么问题?
namespace MetroAlarm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string time;
public DateTime nextTime;
private void Form1_Load(object sender, EventArgs e)
{
UpdateTime();
UpdateNext();
}
public void UpdateTime()
{
time = DateTime.Now.ToString("h:mm:ss tt");
LBLTime.Text = time;
LBLNext.Text = nextTime;
}
public void UpdateNext()
{
if (DateTime.Now <= Metro1)
{
nextTime = Metro1;
}
if(DateTime.Now >= Metro1)
{
nextTime = Metro2;
}
if (DateTime.Now >= Metro2 )
{
nextTime = Metro3;
}
if (DateTime.Now >= Metro3)
{
nextTime = Metro4;
}
if (DateTime.Now >= Metro4)
{
nextTime = Metro5;
}
if (DateTime.Now >= Metro5)
{
nextTime = LastMetro;
}
}
private void UpdateClock_Tick(object sender, EventArgs e)
{
UpdateTime();
UpdateNext();
}
DateTime Metro1 = Convert.ToDateTime("7:57:00 AM");
DateTime Metro2 = Convert.ToDateTime("8:09:00 AM");
DateTime Metro3 = Convert.ToDateTime("8:20:00 AM");
DateTime Metro4 = Convert.ToDateTime("8:33:00 AM");
DateTime LastMetro = Convert.ToDateTime("8:45:00 AM");
}
}
答案 0 :(得分:2)
你需要这样的Timer
:
Timer timer1 = new Timer();
public Form1()
{
InitializeComponent();
timer1.Tick += UpdateClock_Tick;
timer1.Start();
}
另外要在nextTime
中显示LBLNext.Text
,您应该使用ToShortTimeString()
,如下所示:
public void UpdateTime()
{
time = DateTime.Now.ToString("h:mm:ss tt");
LBLTime.Text = time;
LBLNext.Text = nextTime.ToShortTimeString();
}