Anuya
Anuya

Reputation: 8350

How to update the progress bar in runtime using c#

I am using the below code to update my progress bar.

        ProgressBar.Visible = true; 
        ProgressBar.Minimum = 1; 
        ProgressBar.Maximum = PortCount; 
        ProgressBar.Value = 1; 
        ProgressBar.Step = 1; 

        int intdata = 5;
        for (int x = 1; x <= intdata; x++)
          {
            ProgressBar.PerformStep();
        }

        MessageBox.Show("Done");

But, it is not getting updated during runtime. Is it because the progress bar is in the same thread. If so, how to update this progress from another thread.

Upvotes: 4

Views: 19347

Answers (2)

Josh
Josh

Reputation: 69262

Is this Windows Forms? Calling Refresh() on the ProgressBar should do it. You could also use Application.DoEvents though which will let your UI respond to user input instead of locking up during the process.

A better idea would be to use the BackgroundWorker class. Do the work on the background thread and send progress updates to the UI thread via the ReportProgress method. This keeps your UI thread responsive.

Upvotes: 6

leppie
leppie

Reputation: 117220

You are not giving the message pump time to update the control.

Although either of these are bad, you can do:

  • Call Refresh on the control
  • Call Application.DoEvents

Upvotes: 6

Related Questions