简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM