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?

女生的网名这么多〃 提交于 2019-12-13 07:37:58

问题


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

So what am I trying to do?

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;
        }

回答1:


Try the other way around:

    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();
    }

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;
            };



回答2:


Make sure you're using the System.Windows.Forms.Timer class, which calls the tick event on the UI thread.



来源:https://stackoverflow.com/questions/14802579/how-do-i-set-the-contents-of-a-label-and-have-it-reset-to-string-empty-after-a-p

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!