0

I am trying automatic write data to textbox9. I am using timer, but I don't find why it's not working. Maybe somebody have suggest for me.

System.Timers.Timer aTimer;
public int i;

private void Form1_Load(object sender, EventArgs e)
{
  i = 0;
  aTimer = new System.Timers.Timer();
  aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimeEvent);
  aTimer.Interval = 2000;
  aTimer.Enabled = true;
}

public void OnTimeEvent(object source, System.Timers.ElapsedEventArgs e) 
{
   i = i + 1;  
   textBox9.Text = i.ToString();         
}
Quercus
  • 2,015
  • 1
  • 12
  • 18
  • Use the Timer from the TOOLBOX. It was designed for use with WinForms. Drop it on your form, set the Interval and whether it is Enabled to start with. Double click it to get the `Tick()` event. Put your code in there.... – Idle_Mind Nov 18 '20 at 21:24

2 Answers2

1

First, you need to move the "aTimer" and the "i" variables outside the methods at declare them at the form level. In the code you provided, those variables are not declared anywhere.

Second, the System.Timers.Timer will run outside the main thread, and it is not safe to access a control (textbox) from its events. So, you need to use the System.Windows.Forms.Timer, like so:

private System.Windows.Forms.Timer aTimer;
private int i = 0;

private void Form1_Load(object sender, EventArgs e)
{
    i = 0;
    aTimer = new System.Windows.Forms.Timer();
    aTimer.Tick += ATimer_Tick;
    aTimer.Interval = 2000;
    aTimer.Enabled = true;
}

private void ATimer_Tick(object sender, EventArgs e)
{
    i = i + 1;
    textBox9.Text = i.ToString();
}
JesseChunn
  • 555
  • 3
  • 7
0

System.Timers.Timer by default calls its Elapsed in thread from a pool, different from main and attempt to change UI control from that thread should fire an exception.
You need to assign it SynchronizingObject:

aTimer.SynchronizingObject = this; // this = form

Or use System.Windows.Forms.Timer which is timer component designed for UI.

Quercus
  • 2,015
  • 1
  • 12
  • 18