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?
Windows. Forms namespace. Add a Label control to the form - Click Label in the Toolbox and drag it over the forms Designer and drop it in the desired location. If you want to change the display text of the Label, you have to set a new text to the Text property of Label.
On the tab "Properties" just click on the arrow to show all controls and click on the label you want, this will automatically select the label on your form..
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. Show activity on this post.
While the UI thread is busy running your code it cannot process the application message pump and cannot repaint anything, including your label. You have to move your work to a background thread, a Task or BackgroundWorker.
This can be done in a couple of ways... First, your "background" thread could update some kind of "CurrentStatus" string variable that it changes as it goes along. You could then put a timer on your form that would then grab the CurrentStatus variable and update the label with it.
yes, I tried the invoker and creating a new label but still not working. The content of this label updates only if I provide the focus to my form. The crazy thing is that all other labels are updating immediately without have to wait to receive focus. i'm sorry but i have no more ideas.
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.
You should be doing this on another thread, and then updating your UI thread from that thread. You are blocking further processing by performing this work on the UI thread.
If you can't move this code to the UI thread, then you could always call Application.DoEvents
, but I strongly suggest you explore these options first:
System.ComponentModel.BackgroundWorker
System.Threading.ThreadPool
System.Threading.Thread
System.Threading.Tasks
namespaceIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With