How to use Timer control in C#
By FoxLearn 11/22/2024 8:16:01 AM 4.38K
In C# Windows Forms applications, the Timer
control is an invaluable tool for executing repetitive tasks at fixed intervals. In this article, we will explore a simple example of how to use the Timer
control to increment a value displayed in a textbox.
How to use Timer control in C#?
Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "TimerControl" and then click OK
Drag and drop the TextBox, Button and Timer controls onto your form, then design your form as shown below.
Add code to handle your form as shown below.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TimerControl { public partial class Form1 : Form { int value; public Form1() { InitializeComponent(); } } }
int value
: This integer holds the current value to be displayed in the TextBox
. It is incremented each time the timer ticks.
The timer1_Tick
event handler is where the main logic for updating the value happens. Every time the timer ticks, this method is executed, and the value is incremented.
private void timer1_Tick(object sender, EventArgs e) { // Update the textbox with incremented value txtValue.Text = (value++).ToString(); }
When the user clicks the Start
button (btnStart
), the following code is executed:
// Start the timer private void btnStart_Click(object sender, EventArgs e) { // Parse the value from the textbox and start the timer if (int.TryParse(txtValue.Text, out value)) { timer1.Start(); } }
The int.TryParse
method ensures that the value in the TextBox
is a valid integer before starting the timer. If the value is valid, timer1.Start()
is called, which begins the timer and triggers the timer1_Tick
event at intervals defined by the Interval
property of the Timer
.
The Stop
button (btnStop
) allows the user to stop the timer. When clicked, the following code is executed:
// Stop the timer private void btnStop_Click(object sender, EventArgs e) { timer1.Stop(); }
The Timer
control executes the Tick
event at a fixed interval. By default, the Interval
property is set to 100 milliseconds, but you can change it based on how frequently you want the timer to tick.
The example demonstrates a Windows Forms application where the value displayed in a TextBox
is incremented every time a Timer
ticks. The user can start and stop the timer using two buttons (Start
and Stop
).
VIDEO TUTORIAL
- How to make a File Explorer in C#
- How to create multi language using Resource Manager and Culture Info in C#
- How to Load selected columns data in DataGridView in C#
- How to Search DataGridView by using TextBox in C#
- How to read .rtf file in C#
- How to read text file (*.txt) in C#
- How to make an Alarm clock in C#
- How to Save and Retrieve Image from SQL database in C#