Search code examples
c#.netprogress-bar

How to update progress bar from other class?


I have a command line tool written in c# (that i have the source of) that I am making a gui for in visual studio 2010. In the gui I want to update the progress bar to reflect the progress of the tools operations. How would I signal from inside the tool that progress has been made and to update the progress bar? Some simplified example code of what im doing.

private void doThings_Click(object sender, EventArgs e)
{
  myToolInstance.doWorkThatNeedsToReportProgress();
}

The work that is being done by the tool is a series of function calls, normally around 30. I want to update the progress bar each time one of those finishes.


Solution

  • Create a public property or a public method in the form containing the progress bar

    public void SetProgress(int progress)
    {
        progressBar.Progress = progress;
    }
    

    Now you can update the progress bar with

    myForm.SetProgress(50);
    

    Another approach is to have a ProgressChanged event somewhere and let the form subscribe to this event.

    public class Tool {
        public event Action<int> ProgressChanged;
    
        private void OnProgressChanged(int progress) 
        {
            ProgressChanged?.Invoke(progress);
        }
    
        public void DoSomething()
        {
            ...
            OnProgressChanged(30);
            ...
        }
    }
    

    In the form you would have something like this

    private Tool _tool;
    
    public MyForm () // Constructor of your form
    {
        _tool = new Tool();
        _tool.ProgressChanged += Tool_ProgressChanged;
    }
    
    private void Tool_ProgressChanged(int progress)
    {
        progressBar.Progress = progress;
    }