Question

I have a windows form where I want the time to constantly be updated. Right now it will take the current time from when the program was started.

For example, if I started the program at 5:30:29 PM that is what it will show the whole time the program runs.I need it to constantly be updated as the seconds tick by. So, If I started the program at 5:30:29 PM and ran it for exactly 5 minutes, the time displayed then should be 4:35:29 PM.

i want to do this in .Net

Was it helpful?

Solution

You need to use a Timer control and set the time interval to 1 second i.e. 1000 and for each Timer tick, update the current time. For example here is the C# solution, assume the timer timer1 and lets say you want to show the time at the label dateTimeLbl.Text then here is the timer1_tick event:

    private void timer1_Tick(object sender, EventArgs e)
    {
        dateTimeLbl.Text = DateTime.Now.ToLongTimeString();
    }

OTHER TIPS

Add a Timer control to your Form.

Set the Interval to be 500

This is a value in milliseconds so it ensures that it fires twice a second. If you use 1000 for one second your time could be (at worst case) nearly a second out because you don't know when in the second it will fire.

Set the Enabled property to True

Then update your display every time the timer ticks

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    lblTime.Text = DateTime.Now.ToLongTimeString
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top