Use a ProgressBar in C#


This example shows how to use a ProgressBar to show the progress of a long task. This is a very simple example that performs a synchronous task.

I created the ProgressBar at design time. I left its Minimum property set to 0 and its Maximum property set to 100, although you can change those values if you like.

When you click the Go button, the following code executes.

private void btnGo_Click(object sender, EventArgs e)
    long max = long.Parse(txtMax.Text, NumberStyles.Any);
    long tenth = max / 10;
    long leftover = max - 9 * tenth;
    for (int round = 0; round < 9; round++)
        prgCount.Value = round * 10;
        for (long i = 0; i < tenth; i++) { }
    prgCount.Value = 90;
    for (long i = 0; i < leftover; i++) { }
    prgCount.Value = 100;
    tmrHideProgressBar.Enabled = true;

This code reads the number you entered in the text box and divides it by 10. It then performs 9 loops. During each loop the program updates the ProgressBar to show the amount of the task that is complete and then counts to 1/10th of the value that you entered.

After it has finished the 9 loops, the program counts out any remaining numbers that you specified. If the total number is evenly divisible by 10, then this is the last 1/10th of the numbers. If the total isn’t divisible by 10, then this is whatever is left over after the 9 loops.

All of these loops just simulate a long task. In a real program you would do something more useful like processing records in a database.

After that last loop, the program is done so it could hide the ProgressBar. Unfortunately if you do that, the ProgressBar disappears so quickly that the user doesn’t see it at 100% done and that seems a bit uncomfortable. (Try it and see.)

To avoid that, the program enables a Timer named tmrHideProgressBar. The following code shows the timer’s Tick event handler.

private void tmrHideProgressBar_Tick(object sender, EventArgs e)
    tmrHideProgressBar.Enabled = false;

This code hides the ProgressBar and then disables the timer. At design time I set the timer’s Interval property to 500 so the ProgressBar remains visible at 100% filled for half a second before disappearing.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in controls, user interface and tagged , , , , , , , , , , . Bookmark the permalink.