How can I update the value of a Label control periodically?

无人久伴 提交于 2019-12-02 12:59:07

From your questions, it seems you need to change the value of something like a status label to display information periodically to the user. If you are using winforms, you can use a timer and a delegate like this:

From your questions, it seems you need to change the value of something like a status label to display information periodically to the user. If you are using winforms, you can use a timer and a delegate like this:

//First create a delegate to update the label value
public delegate void labelChanger(string s);

//create timer object
Timer t = new Timer();

//create a generic List to store messages. You could also use a Queue instead.
List<string> mod = new List<string>();

//index for list
int cIndex = 0;

//add this in your Form Load event or after InitializeComponent()
t.Tick += (timer_tick);
t.Interval = 5000;//how long you want it to stay.
t.Start();

//the timer_tick method
private void timer_tick(object s, EventArgs e)
{
     labelWarningMessage.Invoke(new labelChanger(labelWork), mod[cIndex]);
     cIndex++;
}

//the method to do the actual message display
private void labelWork(string s)
{
     labelWARNING.Visible = true;
     labelWarningMessage.Text = "This module has a prerequisite module: " + s;
}

I hope that helps. Good Luck.

EDIT: Thought I posted this code long ago only to come back and find out I didn't...but maybe someone might find it useful.

Also, this method will be redundant in this case, since creating the Timer alone will work without the use of a delegate and is only useful for the delegate usage and UI thread access part.

I would use another thread for it:

labelWARNING.Visible = true;
labelWarningMessage.Text = "This module has a prerequisite module: " + item;
new Thread(() => {
    Thread.Sleep(5000);
    Dispatcher.BeginInvoke((Action)(() => { labelWARNING.Visible = false; }));
}).Start();

(this is for WPF, for WinForms should be essentially the same)

I used a timer.

private void timer1_Tick(object sender, EventArgs e)
{        
      labelWarningMessage.Text = "";
      labelWARNING.Visible = false;
}

Updated for async/await. This will

// Update all text with warning message
foreach (var x in mod)
{
      labelWARNING.Visible = true;
      labelWarningMessage.Text = "This module has a prerequisite module: " + x;
}

// Wait 1 second or 1000ms    
await Task.Delay(1000);

// Now dismiss the message
foreach (var x in mod)
      labelWarningMessage.Text = "";

The surrounding function needs to be an public async Task SomeMethod() or
public async void buttonClick(object sender, RoutedEventArgs e)
to use the await keyword

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