maniac84
maniac84

Reputation: 517

Display a running date and time in a textbox in C#

I've try searching in this website ways to display date and time. But all the example here shows only static date and time. Is there a way to display date and time which is running or I should say increment every second? Does it involve updating the time every second?

Upvotes: 2

Views: 35651

Answers (5)

Eiconic
Eiconic

Reputation: 4346

There is a Delay method in Task, which takes milliseconds as an input. For me the code for the Time update is like as below,

Using System.Threading.Tasks;    
async void TimeUpdater()
    {
        while (true)
        {
            TxtTime.Text = DateTime.Now.ToString();
            await Task.Delay(1000);
        }
    }

This will update the UI and wait for 1 Second and then again iterate over, for infinite times. Also don`t forget to make the method async, because of the await operator. As I`ve researched this is the easiest method to get a running date and time in the UI weather WinForms or WPF.

Upvotes: 0

JohnnBlade
JohnnBlade

Reputation: 4327

Use a timer object and in the tick event show the date in the textbox in winforms use

System.Windows.Forms.Timer tmr = null;
private void StartTimer()
{
    tmr = new System.Windows.Forms.Timer();
    tmr.Interval = 1000;
    tmr.Tick += new EventHandler(tmr_Tick);
    tmr.Enabled = true;
}

void tmr_Tick(object sender, EventArgs e)
{
    myTextBox.Text = DateTime.Now.ToString();
}

Upvotes: 12

cloudguy
cloudguy

Reputation: 1

Use a timer with an interval of 1 second. If your app is winforms, use timer from windows.forms namespace http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx , it runs in the same thread as gui, so it is safe to update gui. You also can use timer from system.threading namespace, but in this case you should update controls in thread-safe manner by calling invoke method http://msdn.microsoft.com/en-us/library/ms171728.aspx. If your app is web, use javascript instead

Upvotes: 0

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

You're right in your second option.

It's all about using a timer and update TextBox with current time.

Upvotes: 1

Eric J.
Eric J.

Reputation: 150148

You can add a Timer to your form. Set it to fire once per second. In the event handler for your timer, update the text box with the current time.

Upvotes: 1

Related Questions