Click here to Skip to main content
15,886,840 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm using the following code:

C#
private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }


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

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("Complete");
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            int[] arr = new int[20];
            for (int i = 1; i <= 20; i++)
            {
                arr[i] = i;
                Thread.Sleep(100);
                backgroundWorker1.ReportProgress(i);
            }
        }

This only increments the progress bar only to 20% by the time the control exits the for loop. I want the progress bar to increment to 100% by the time the for loop completes the 20 loops proportionally. eg/- the progress bar should increment by 5% (as in (1/20)*100)) after the first loop is complete . Please help.
Posted

1 solution

As you could probably guess from the parameter name, the first argument to the ReportProgress method is the percentage returned from the ProgressPercentage property of the ProgressChangedEventArgs class.

You are only passing in values between 1 and 20, which is why the progress bar never gets above 20%.

Convert the values to a percentage before passing them to the ReportProgress method:
C#
backgroundWorker1.ReportProgress(i * 5);
 
Share this answer
 
Comments
Richard Deeming 16-Oct-14 13:52pm    
Make sure the event handler is still attached.
Debug the code to make sure the DoWork handler completes.
Add a breakpoint in the RunWorkerCompleted handler to see if it's being triggered.
Tejas Shastri 16-Oct-14 13:52pm    
it worked.. Thank you.. I actually tried to pass it in a different way earlier but it hadn't worked.. Thanks :)
BillWoodruff 16-Oct-14 16:13pm    
+5
Maciej Los 16-Oct-14 17:09pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900