Using the ProgressBar Control

Using the ProgressBar Control

The ProgressBar control is used to provide visual feedback to the user regarding the status of a task, usually for tasks that exceed a short duration. For example, a ProgressBar control can be used to display the progress of a task that copies a number of files or populates a database table.

The ProgressBar control consists of a bar that’s filled as an operation progresses. Because the progress bar is often used to display the percentage of a task that’s been completed, the default minimum and maximum values are optimized for this common case. The default minimum value is set to 0, and the default maximum value is set to 100.

One reason to change the range of values for a ProgressBar control is to simplify working with a specific number of items. You can adjust the lower boundary with the Minimum property, as shown here:

progressBar.Minimum = 50;

The Maximum property is used to adjust the upper end of the range:

progressBar.Maximum = 125;

The following two methods are used to change the value displayed in the ProgressBar control:

  • PerformStep  Updates the control’s value by the amount specified by the Step property

  • Increment  Updates the control’s value by the amount specified in the method’s parameter

Typically, you’ll use the PerformStep method to increment the control a fixed number of times, as shown here:

private void timer_Tick(object sender, System.EventArgs e)
{
    progressBar.PerformStep();
    if(progressBar.Value == progressBar.Maximum)
    {
        // Timer period elapsed.
        
    

    }
}

In addition to Maximum and Minimum, commonly used properties exposed by the ProgressBar class include the following:

  • Value  The current position of the progress bar

  • Step  The amount that the progress bar is incremented when the PerformStep method is called

The following code uses the Value property to update a label control with the current progress:

progressBar.PerformStep();
progressLabel.Text = string.Format("{0}% complete", progressBar.Value);

You also can use the Value property to explicitly set a new value for the control, as shown here:

progressBar.Value = 75;


Part III: Programming Windows Forms