Search code examples
c#progress

Progress bar percentage


Could someone please tell me how I can get the correct percentage progress figure? I'm getting values going above 100% - Can't seem to get my head around it.

Thanks

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
        string[] strArray = txtSource.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        Int32 i = 0;

        foreach (string item in strArray)
        {
            //Thread.Sleep(250);

            string returnMessage = DoAction(item).Replace(nl,"");
            i++;

            backgroundWorker.ReportProgress(i, item + " ..." + returnMessage);                
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
        lblProgress.Text = "Progress: " + e.ProgressPercentage.ToString() + "% complete, processing: " + e.UserState.ToString();
        txtResults.Text += "Processing " + e.UserState.ToString() + nl;
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        btnRun.Enabled = true;
        lblProgress.Text = "Action completed!";            
    }

Solution

  • Since you're increasing i on each iteration on strArray, it is incorrect to use i as percent of execution here just because it will be exact percent of execution if and only if your array contains 100 items:

    backgroundWorker.ReportProgress(i, item + " ..." + returnMessage);
    

    You can simply use (100 * i) / strArray.Length instead.