1

I want to print "ms" value in textbox1 by clicking the button firstly, then it should wait for 100ms (one by one), then it show next value.

But it's showing only the last value by clicking button, still after coding Thread.Sleep(100). It should show the value like stop watch.

private void button1_Click(object sender, EventArgs e)
{            
     int ms = 00;    
     for (ms = 0; ms < 10; ms++)
    {                           
        textBox1.Text = ms.ToString();                    
        Thread.Sleep(100);
        textBox1.Text = "";
    }         
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
hemant
  • 11
  • 1
  • 2

2 Answers2

1

Thats because you button click is running on the gui thread and will block painting.

You could try updating the textbox:

private void button1_Click(object sender, EventArgs e)
{
    int ms = 00;
    for (ms = 0; ms < 10; ms++)
    {
        textBox1.Text = ms.ToString();
        textBox1.Update();
        Thread.Sleep(100);
        textBox1.Text = "";
    }

}

But this will still block you gui thread. If you don't want to block the current thread, you could create a new Thread that invokes the gui thread to alter the textBox1.Text.

Writing to a TextBox from another thread?

Community
  • 1
  • 1
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
1

The reason your textbox only shows tha last value is because your code runs on the UI thread. The UI doesn't get the time to update its layout until your code has reached its end. You could solve this by using some sort of background threading mechanism so that the UI has the time and resources to update itself.

  • You could use timers and update the textbox text on its tick event.
  • You could use task await to enforce background threading instead of Thread.Sleep

    private async void button1_Click(Object sender, EventArgs e)
    {
        for (int ms = 0; ms < 10; ms++)
        {
            textBox1.Text = ms.ToString();
            await Task.Delay(100);
        }
    }
    
Djohnnie
  • 11
  • 2