Hasan

Hasan

  • NA
  • 50
  • 0

Problem while restarting a Timer control in a winform application

Jul 18 2008 11:59 PM

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

Faysal 

 


Answers (2)