Search code examples
c#winformsprogress-barbackgroundworker

C# : Show progress bar change in custom message box


I have a 2 forms, MainForm and ProgressForm.

#1 MainForm.cs has a button, which when clicked starts my backgroundWorker1.

 ProgressForm pg = new ProgressForm(); 

 private void StarBtn_Click(object sender, EventArgs e)
        {
           
           pg.Show();
           
            if(!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
            }
        }

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
          //time consuming tasks...
        }

#2 ProgressForm is where I have added a progress bar and a label.

namespace MainApp
{
    public partial class ProgressForm : Form
    {
        public ProgressForm()
        {
            InitializeComponent();
        }

    }
}

I need to show the progress of my background process in MainForm to progressBar1 in ProgressForm (as below)

 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
           //something like..
           //this.progressBar1.Value = e.ProgressPercentage;
           //in ProgressForm...
            
        }

and show a completed in label and close the form.

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
           //label.Text = "Completed"
          // Close the ProgressForm...
            
        }

How can I access the elements in ProgressFrom from backgroundworker in MainForm and make the progress update.


Solution

  • Your background worker events are in the MainForm? If so then add public properties to your ProgressForm and set the label and / or progress bar accordingly to the provided values.

    ProgressForm

    public int Progress {
    set {
        progressBar1.Value = value;
      }
    }
    public string LabelText{
    set {
       label.Text = value;
      }
    }
    

    MainForm

    pg.Progress = e.ProgressPercentage;