bladekel
bladekel

Reputation: 37

C# how to change textbox value by loop?

I need to create a script such as chronometer.

I write a code like following;

for(int i=0;i<50;i++)
{
    textBox.Text = i.Tostring();
    Task.Delay(100).Wait();
}

The expected output is like a chronometer ; an increasing text by 1 up to 49 started from 0 at textbox.

But I get only 49 after a 49*100 miliseconds pause later.

How can I solve this ?

Upvotes: 0

Views: 1628

Answers (1)

Zein Makki
Zein Makki

Reputation: 30022

The event or method running this piece of code needs to be asynchronous. This is in order for the UI to be responsive:

private async void btnDoWork_Click(object sender, EventArgs e)
{
    for(int i=0;i<50;i++)
    {
        textBox.Text = i.Tostring();
        await Task.Delay(100);
    }
}

Otherwise, you'll be blocking the UI Thread and you will not be able to see the Text Box changing. You'll only see the last change which is 49 in your case.

Upvotes: 2

Related Questions