如何在 c# winforms 中设置标签的内容并在 5 秒后将其重置为 string.empty? [英] How do I set the contents of a label and have it reset to string.empty after a period of 5 seconds in c# winforms?

查看:23
本文介绍了如何在 c# winforms 中设置标签的内容并在 5 秒后将其重置为 string.empty?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何做到这一点,我曾尝试弄乱计时器,但到目前为止无济于事.

I've no real idea how to do this and I have tried messing with a timer but to no avail so far.

那我想做什么?

我有一个空白的标签.当某个事件被触发时,我希望标签在 5 秒内显示竞争成功设置",然后我希望它恢复为空白.

I have a label that is blank. When a certain event is triggered I want the label to say "Competition successfully setup" for a period of 5 seconds after which I want it to return to being blank.

这真的可以做到吗??它可以?我玩过计时器,但似乎不太理想.

Surely this can be done?? Can it? I have played around with a timer but I seem to be well off the mark.

非常欢迎任何帮助.我的微弱尝试如下.

Any help would be most welcome. My feeble attempt is below.

private void UpdateLabel(object sender, EventArgs e)
        {
            var timer = new Timer()
                {
                    Interval = 5000,
                };
            timer.Tick += (s, evt) =>
                  lblCompetitionSetupSuccess.Text = "Competition successfully setup";

            timer.Start();

            lblCompetitionSetupSuccess.Text = string.Empty;
        }

推荐答案

换个方式试试:

    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "I will vanish in 5 sec";

        var timer = new Timer();
        timer.Interval = 5000;
        timer.Tick += (o, args) => label1.Text = "";
        timer.Start();
    }

首先将标签设置为您希望它显示 5 秒的任何文本

First set the label to whatever text you want it to display for 5 sec

        label1.Text = "I will vanish in 5 sec";

然后设置您的计时器,以便在计时器过去时它将删除文本

Then setup your timer so that on timer elapsed it will remove the text

        var timer = new Timer();
        timer.Interval = 5000;
        timer.Tick += (o, args) => label1.Text = "";
        timer.Start();

如果您希望计时器在第一个计时器结束后停止:

If you want the timer to stop after the first timer elapse:

        timer.Tick += (o, args) =>
            {
                label1.Text = "";
                timer.Enabled = false;
            };

这篇关于如何在 c# winforms 中设置标签的内容并在 5 秒后将其重置为 string.empty?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆