Mahesh Wagh
Mahesh Wagh

Reputation: 161

Changing Time On MaskedTextbox

I want to design changing time on maskedtextbox in my application like windows where time changes on every second. I have set maskedtexbox1 as below:

maskedTextBox1.Text = DateTime.Now.ToShortTimeString();

which is showing current system short time but it’s not changing on every second like windows. How to do?

I'm on Visual Studio 2005, and .NET is below 3.5.

Upvotes: 3

Views: 1565

Answers (3)

cuongle
cuongle

Reputation: 75326

You can use System.Windows.Forms.Timer to update textbox value every second for example:

var timer = new Timer();
timer.Interval = 1000;

timer.Tick += delegate
            {
                textBox1.Text = DateTime.Now.ToLongTimeString();
            };

timer.Start();

Upvotes: 1

Konrad Viltersten
Konrad Viltersten

Reputation: 39278

I'd use the timer and fire an event every second to update the time.

  1. Create a timer (an instance of class Timer in the package System.Windows.Forms).
  2. Set its frequency to 1 second (i.e. 1000 milliseconds).
  3. Tell it what method to call when it goes off (the event handler Kaboom).

Somewhere in your executable code you do that by typing the following.

Timer ticker= new Timer();
ticker.Interval = 1000;
ticker.Tick += new EventHandler(Kaboom);

In the same class (or, if you're confident how to do it, somewhere where you can reach the code) you also create the handler for the fired event of ticking, so that the promise you made about a method to be called when the timer goes off is kept.

private void Kaboom(Object sender, EventArgs eventArgs)
{
  // Execute the tickability code
  MaskedTextBox1.Text = DateTime.Now.ToShortTimeString();
}

Also, don't forget to actually start your ticker when you feel that you're ready.

MyTimer.Start();

Tada!

EDIT:

For the sake of completeness, I'm also going to paste in a part of the reply of @CuaonLe (a higher threshold of competence and requirement for .NET 3.5 or newer).

Timer timer = new Timer { Interval = 1000 };
timer.Tick += (obj, args) 
  => MaskedTextBox1.Text = DateTime.Now.ToLongTimeString();
timer.Start();

Upvotes: 1

corlettk
corlettk

Reputation: 13574

I guess you'll need to setup a Timer which updates your maskedTextBox1 every second.

For how to do that, please see: Add timer to a Windows Forms application

Cheers. Keith.

Upvotes: 1

Related Questions