Update Label while processing in Windows Forms

Picflight picture Picflight · Feb 20, 2009 · Viewed 77.9k times · Source

What is the best way to update a label on a Windows Forms application while processing?

I have a loop that does some processing to files on the user's system when the user clicks a button.

foreach (System.IO.FileInfo f in dir.GetFiles("*.txt"))
{
   // Do processing
   // Show progress bar
   // Update Label on Form, "f.Name is done processing, now processing..."
}

What would be some sample code?

What exactly is this called? Is it threading or delegates?

Answer

Patrick McDonald picture Patrick McDonald · Feb 20, 2009

A quick fix for you would be:

Label1.Text = f.Name + " is done processing, now processing...";
Label1.Refresh();

You really want to avoid DoEvents, otherwise you'll have problems if your user repeatedly presses buttons on your form.