Pages

Ads 468x60px

Thursday, August 16, 2012

ProgressBar not Updating Fix - C#

It has been sited by many StackOverflow questions that, usually when using a BackgroundWorker, your ProgressBar will not update correctly when using C#. I do not know why this happens, however some people suggest that it is because of the threaded interface in Windows Vista and Windows 7.The ProgressBar would get to about 75% full when it should have been at its maximum, and would revert back to 0% before it was fully drawn. Here is what that looked like:

And this is the example code I used:
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 1; (i <= 100); i++)
            {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(20);
                    backgroundWorker1.ReportProgress((i ));
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            if (progressBar1.Maximum == e.ProgressPercentage)
                progressBar1.Value = 0;
        }

However, Mark Lansdown from StackOverflow found a very useful solution, taken from this question.

What he suggested is to draw the value, then draw the value minus 1, because that would force a redraw on the ProgressBar. To to that, I just changed my ProgressChanged event to:

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            if (e.ProgressPercentage != 0)
                progressBar1.Value = e.ProgressPercentage - 1;
            progressBar1.Value = e.ProgressPercentage;
            if (progressBar1.Maximum == e.ProgressPercentage)
                progressBar1.Value = 0;
        }

And the result is that the ProgressBar will now be smoothly redrawn to 100% before it is reverted.

And while this is most certainly strange behavior, I can verify that it works, and now the ProgressBar will fill all the way up.

I hope you enjoyed!

4 comments:

  1. here is simple progressbar program in C#

    http://csharp.net-informations.com/gui/cs-progressbar.htm

    nicol

    ReplyDelete
  2. Progressbar Not Updating Fix - C >>>>> Download Now

    >>>>> Download Full

    Progressbar Not Updating Fix - C >>>>> Download LINK

    >>>>> Download Now

    Progressbar Not Updating Fix - C >>>>> Download Full

    >>>>> Download LINK tE

    ReplyDelete