TaterKing
TaterKing

Reputation: 75

How to change Label text after seconds?

I have searched and tried many approaches to this problem.

With a Visual Studio 2015 WinForma app, I want a Label's text to change after a time delay.

Of my many approaches, I can confirm the string value of the label has changed with a MessageBox, but the onscreen UI does not change.

So far I have tryed:

1: Thread.Sleep(number) inside Public Form1() before I change the value.
Result: doesn't seem to update the UI before the end of the function.

2: nameoflabel.refresh(); EVERYWHERE.
Result: does not do anything anywhere.

3: use System.Timers and change the value of my Label inside the Timer's elapsed function.
Result: changes the value of Label but is not seen onscreen.

4: since everything involving a button click works perfectly to change my label text, I reseached how to imitate a button click with buttonName.preformClick() and made a fake button for the purpose.
Result: value changes but still nothing changes on screen.

I am starting to believe this must be a bug. Yes? No? Anyway, here is what I need to work:

public partial class Form1 : Form
{
    public System.Timers.Timer holder;
    Label say;

    public Form1()
    {
        InitializeComponent();

        say = new Label();
        say.Text="start text";
        this.Controls.Add(say);
        holder = new System.Timers.Timer(5000);
        holder.Elapsed += new ElapsedEventHandler(holdone); 
        holder.Enabled = true;
    }

    public void holdone(Object source, ElapsedEventArgs e)
    {
        //messagebox is correct but onscreen gui is not
        say.Text = "new after seconds";
        MessageBox.Show(say.Text);
    }
}

Upvotes: 2

Views: 3737

Answers (2)

Rufus L
Rufus L

Reputation: 37020

You can use a System.Windows.Forms.Timer instead, which will update the UI as you want:

public partial class Form1 : Form
{
    private System.Windows.Forms.Timer holder;
    private System.Windows.Forms.Label say;

    public Form1()
    {
        InitializeComponent();

        say = new Label {AutoSize = true, Text = "start text"};
        Controls.Add(say);

        holder = new Timer {Interval = 5000};
        holder.Tick += HolderTick;
        holder.Enabled = true;
    }

    private void HolderTick(object sender, EventArgs e)
    {
        say.Text = $"new after {holder.Interval / 1000} seconds";
        holder.Enabled = false;
    }
}

Upvotes: 3

schulmaster
schulmaster

Reputation: 443

public void holdone(Object source, ElapsedEventArgs e)
{
     say.Invoke((MethodInvoker)delegate
    {
        say.Text = "new after seconds"; //predicated upon a declared var say = new Label()
    }); 
} 

This is an example of a System.Timers.Timer Elapsed event handler that should (relatively) immediately affect your UI.

Upvotes: 1

Related Questions