beyond n00b Question - time in c#

Soldato
Joined
6 Jan 2006
Posts
4,663
Location
Newcastle
its annoying me this

Im trying to display current time in a label on my program however it just takes the system time of openning/compiling the app I tried a for loop but that crashed my program Ive tried this method

Code:
                        int hours = DateTime.Now.Hour;
            int minutes = DateTime.Now.Minute;
            int seconds = DateTime.Now.Second;
            int milSeconds = DateTime.Now.Millisecond;

            string timeString = hours + " : " + minutes + " : " + seconds + " : " + milSeconds;

            _timelabel.Text = timeString;

and this method



Code:
            string time;
            time = DateTime.Now.ToString(); 

            _timelabel.Text = "Current Time:" + time;

both with the for loops, tried putting the code in both public and private voids and form load ... and still not a clue


please help :rolleyes:
 
Soldato
Joined
18 Oct 2002
Posts
3,926
Location
SW London
Well, in the first one you're trying to concatenate integers with strings, so it won't work.

Second one looks like it should work though, what's the exception it's throwing?

EDIT. Just reread your question and I see what you're getting at.
You need to look at the Timer class - http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

The one in the System.Windows.Forms namespace is probably most appropriate for you if you're interacting with the GUI, otherwise you'd need to marshal the call back to the GUI thread.
You need to set up a timer with an appropriate interval (e.g. 1000 if you want it to update every second)
Then set up an event handler for the timer Tick event that sets the time in your label.

That should then update the label every second and display the current time.
 
Last edited:
Soldato
Joined
16 May 2005
Posts
6,509
Location
Cold waters
As you know, if you only create the string once then it will be set in stone at the time that happened in your running program (not when you compile).

You can't use an (infinite?) for loop to keep updating the label on your GUI application because your window won't get a chance to update itself and it will seem to have frozen.

This creates and starts a timer to swoop in to the GUI thread once a second and update the label.

Code:
System.Windows.Forms.Timer timeUpdater = new Timer()
{
    Interval = 1000, // milliseconds
};

timeUpdater.Tick += delegate
{
    _timelabel.Text = DateTime.Now.ToLongTimeString();
};

timeUpdater.Start();
 
Back
Top Bottom