Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 693
Whyrusleeping Avatar asked Jun 28 '12 20:06

Whyrusleeping


People also ask

How to update progress bar from another class c#?

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); ... } }

How do you change how much of the progress bar is filled in?

By default, the progress bar is full when the progress value reaches 100. You can adjust this default by setting the android:max attribute. Other progress bar styles provided by the system include: Widget.


1 Answers

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;
}
like image 140
Olivier Jacot-Descombes Avatar answered Sep 28 '22 02:09

Olivier Jacot-Descombes