[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use a ProgressBar in C#

[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; prgCount.Show(); 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) { prgCount.Hide(); 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.