Hi All,
I am facing a vary basic problem with timer. I want a timer to start counting an integer i with a start-button-press and stop counting with a stop-button-press. Then start counting again with start-button-press and so on. The code looks like the following sample snippet:
int i=0;
Timer tmrTest = new Timer();
public void OnTimerEvent_test(object source, EventArgs e)
{
i++;
txtCounter.Text = i.ToString();
}
private void btnStartTimer_Click(object sender, EventArgs e)
{
tmrTest.Enabled = true;
tmrTest.Interval = 500;
tmrTest.Tick += new System.EventHandler(OnTimerEvent_test);
}
private void btnStopTimer_Click(object sender, EventArgs e)
{
tmrTest.Enabled = false;
}
The problem is on start-button-press first time it counts i as i+1 but in second start-button-press it counts i as i+2, for 3rd it's i+3 and so on. But I want the counting to be always i=i+1;
May be this is a very simple issue while handling timer but I failed to get any solution. Please help me to solve this out. And tell me the reason, why is this timer behaving like this?
Thanks in advance
HasanPosted Jul 19, 2008, 9:55 PM
Actually u can't understand my question.
However now I know the answer. The problem was in wach button press I was calling a new event handlar with each batton press: tmrTest.Tick += new System.EventHandler(OnTimerEvent_test);
One way to solve my problem is:
tmrTest.Tick -= new System.EventHandler(OnTimerEvent_test);
tmrTest.Tick += new System.EventHandler(OnTimerEvent_test);
Faysal
AlanPosted Jul 19, 2008, 4:15 PM
You need to reset the counter variable 'i' to zero each time you stop the Timer otherwise it will just carry on incrementing the previous value when the Timer is started again:
private void btnStopTimer_Click(object sender, EventArgs e)
{
tmrTest.Enabled = false;
i = 0;
}