How to Show Progress of Fetching Database Records Using a ProgressBar Control in WinForm


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

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

Step 1: Add a ProgressBar control to 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.

The Minimum is the value of when the ProgressBar is completely empty and Maximum is the value of when the ProgressBar is completely filled. The default value of the Minimum property is 0 so we need not change it. But the default value of the 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 the following code in the Button Click event before "backgroundWorker1.RunWorkerAsync(obj);"
    TotalRecords = GetTotalRecords();
    progressBar1.Maximum = TotalRecords;
  • Add code for GetTotalRecords method:

    private int GetTotalRecords()
            using (con = new SqlConnection(ConString))
                cmd = new SqlCommand("SELECT COUNT(EmployeeID) FROM Employees", con);
                TotalRecords = int.Parse(cmd.ExecuteScalar().ToString());
        catch (Exception ex)
        return TotalRecords;
  • Add the following code in the ProgressChanged event of the BackgroundWorker:
    progressBar1.Value = e.ProgressPercentage;

Note: The Value of the ProgressBar.Value property should be between the Minimum and Maximum values.

Final Output: