简体   繁体   English

C#如何通过循环更改文本框值?

[英]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. 在文本框中从0开始将文本从1增加到49。

But I get only 49 after a 49*100 miliseconds pause later. 但是经过49 * 100毫秒的暂停后,我只有49。

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: 这是为了使UI能够响应:

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. 否则,您将阻止UI线程,并且您将无法看到文本框发生变化。 You'll only see the last change which is 49 in your case. 在您的情况下,您只会看到最后的更改是49。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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