Zet
Zet

Reputation: 571

Windows Forms - display changing values

In a Form I'm trying to display changing value in a TextBox:

private void MyButton_Click(object sender, EventArgs e)
{
    for (int i = 0; i < 10; i++)
    {
        Start(i);
    } 
}
public void Start(int i)
{
    textBox1.Text = i.ToString();
    Thread.Sleep(200);
}

Only last value of the loop is displayed. Why?

Upvotes: 0

Views: 903

Answers (1)

gunnerone
gunnerone

Reputation: 3572

There's a thread called a UI thread, which is responsible for updating the GUI. When the button is clicked this event runs on the UI thread. So your Start function is also running on the UI thread. The UI thread is busy running the Start function so it doesn't have a chance to update the textbox until the Start function completes. Once the Start function completes the UI thread updates the textbox to the last value.

What you need to do is run your Start function on another thread, so the UI thread is free to update the textbox. There are a few ways you could do this. Here's one example:

private System.Windows.Forms.Timer _timer;
private int _timer_i;

public Form1()
{
  InitializeComponent();

  _timer = new System.Windows.Forms.Timer()
  {
    Enabled = false,
    Interval = 200
  };
  _timer.Tick += _timer_Tick;
}

private void _timer_Tick(object sender, EventArgs e)
{
  textBox1.Text = _timer_i.ToString();
  _timer_i++;
  if (_timer_i >= 10)
  {
    _timer.Stop();
  }
}

private void button1_Click(object sender, EventArgs e)
{
  _timer.Stop();
  _timer_i = 0;
  _timer.Start();
}

Upvotes: 2

Related Questions