Question

I'm trying to set the value of a textblock to what hour it is, I have the following code:

timeHours.Text = DateTime.Now.Hour.ToString();

But the textblock doesn't show what hour it is, it doesn't show anything and stays as the original text, how do I solve this problem?

Was it helpful?

Solution

If you want to show the current hour in a text box, and have it update properly every 60 minutes then you need some sort of background process that changes the value that is displayed in the textbox. You can do this with a simple Timer object and an event.

using System.Timers;

class myclass
{
    System.Timers.Timer timer;

    public void initialise()
    {
        timer = new System.Timers.Timer(10000);
        timer += new ElapsedEventHandler(_timer_Elapsed);
    }

    void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
    timeHours.Text = DateTime.Now.Hour.ToString();
    }
} 

This updates the hour every 10 seconds (10000 milliseconds), not very efficient but does the job.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top