This article will teach you how you can show the progress bar in Windows applications, using C#.NET. So, for this application, first we will create a new Windows application and add a progress bar control.
Now, we will assign the maximum value to the progress bar control. This will help to show the progress.
After this control setting, we will add a backgroundWorker control.
Now, generate the DoWork and ProgressChanged event for the control backgroundWorker.
After this, we will add the code on DoWork event.
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
- {
- for (int i = 1; i <= 100; i++)
- {
-
- Thread.Sleep(50);
-
- backgroundWorker1.ReportProgress(i);
- }
- }
Now, we will add the code for ProgressChanged.
- private void backgroundWorker1_ProgressChanged(object sender,
- ProgressChangedEventArgs e)
- {
-
- progressBar1.Value = e.ProgressPercentage;
-
- this.Text = e.ProgressPercentage.ToString();
- }
Now, we will add the code to invoke the backgroundWorker.
- private void Form2_Load(object sender, System.EventArgs e)
- {
- backgroundWorker1.WorkerReportsProgress = true;
- backgroundWorker1.RunWorkerAsync();
- }
So, here is the complete code of what we have done.
- using System.ComponentModel;
- using System.Threading;
- using System.Windows.Forms;
-
- namespace WindowsFormsApplication1
- {
- public partial class Form2 : Form
- {
- public Form2()
- {
- InitializeComponent();
- }
-
- private void Form2_Load(object sender, System.EventArgs e)
- {
- backgroundWorker1.WorkerReportsProgress = true;
- backgroundWorker1.RunWorkerAsync();
- }
-
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
- {
- for (int i = 1; i <= 100; i++)
- {
-
- Thread.Sleep(50);
-
- backgroundWorker1.ReportProgress(i);
- }
- }
-
- private void backgroundWorker1_ProgressChanged(object sender,
- ProgressChangedEventArgs e)
- {
-
- progressBar1.Value = e.ProgressPercentage;
-
- this.Text = "Progress: " + e.ProgressPercentage.ToString() + "%";
- }
- }
- }
Now, we are done. Run the application to check the output.