How to show progress of fetching database records using a ProgressBar control in WinForm

In this article we will learn how to show progress of fetching database records using a ProgressBar control in WinForm

Introduction:

In this article we will use ProgressBar control to show progress of fetching database records in a WinForm.

In my last article I used a BackgroundWorker control to fetch database records. I will be using same project in this article. Click here to read my previous article.

Step 1:

Add a ProgressBar control on the Form1 and set its Dock property to Bottom so that it is docked to the bottom edge of the form.

Step 2:

To show progress of a process we need to set a range using Minimum and Maximum property of the ProgressBar. Minimum is the value when the ProgressBar is completely empty and Maximum is the value when the ProgressBar is completely filled. Default value of Minimum property is 0 so we need not change it. But default value of Maximum property is 100 which we will change and set it to the number of records in our table. To show the progress on the ProgressBar we have to set the Value property. We will set e.ProgressPercentage to the Value property so that we can see increasing progress on the ProgressBar for every record fetched from the database.

  • Add following code in Button Click event before “backgroundWorker1.RunWorkerAsync(obj);”
TotalRecords = GetTotalRecords();
progressBar1.Maximum = TotalRecords;
  • Add code for GetTotalRecords method
private int GetTotalRecords()
{
     try
     {
          using (con = new SqlConnection(ConString))
          {
               cmd = new SqlCommand("SELECT COUNT(EmployeeID) FROM Employees", con);
               con.Open();
               TotalRecords = int.Parse(cmd.ExecuteScalar().ToString());
               con.Close();
          }
     }
     catch (Exception ex)
     {
          MessageBox.Show(ex.Message);
     }
     return TotalRecords;
}
  • Add following code in ProgressChanged event of BackgroundWorker
progressBar1.Value = e.ProgressPercentage;

Note: Value of ProgressBar.Value property should be between Minimum and Maximum value.

Final Output:

Leave a Reply

Your email address will not be published. Required fields are marked *