Reputation: 517
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
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
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
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
Reputation: 64943
You're right in your second option.
It's all about using a timer and update TextBox with current time.
Upvotes: 1