Šarūnas Zu
Šarūnas Zu

Reputation: 11

Write data to textbox automatic

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();         
}

Upvotes: 0

Views: 120

Answers (2)

JesseChunn
JesseChunn

Reputation: 595

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();
}

Upvotes: 1

Quercus
Quercus

Reputation: 2065

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.

Upvotes: 0

Related Questions