How To Perform Paging with the DataGrid Windows Control by Using Visual C# .NET

Article translations Article translations
Article ID: 307710 - View products that this article applies to.
This article was previously published under Q307710
Expand all | Collapse all

On This Page

SUMMARY

The DataGrid Web control has built-in Automatic or Custom Paging functionalities; however, the DataGrid Windows control lacks these features. This article demonstrates how to create a simple paging mechanism for the DataGrid Windows control.

The code samples in this article make use of DataSet objects. In ADO.NET, DataSet objects are filled in a single operation and reside in memory all of the time. If you are working with a large DataSet, this article describes how to display the data in chunks or pages programmatically.

This sample uses the Customers table from the Microsoft SQL Server Northwind database as the database backend. If you connect to any other database or to a different table, make sure that you update the code accordingly.

This technique has some limitations. Refer to the Troubleshooting section for more information.

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows NT 4.0 Server
  • Microsoft Visual Studio .NET
  • Microsoft SQL Server 7.0 or later
This article assumes that you are familiar with the following topics:
  • Visual C# .NET
  • ADO.NET fundamentals and syntax

Steps to Add Paging to a DataGrid Windows Control

When you page a DataGrid, you display data in page-size "chunks," that is, one page of records at a time. The sample code to follow copies the DataRow objects for each page from the DataSet in memory to a temporary table. The temporary table is then bound to the DataGrid control.
  1. Open a new Visual C# .NET Windows Application project.
  2. Add DataGrid control, and set its ReadOnly property to True.
  3. Place the following additional controls on Form1, and set their properties as shown below:
    Collapse this tableExpand this table
    ControlName PropertyText Property
    ButtonbtnFirstPageFirst Page
    ButtonbtnNextPageNext Page
    TextBoxtxtDisplayPageNo
    ButtonbtnPreviousPagePrevious Page
    ButtonbtnLastPageLast Page
    TextBoxtxtPageSize5
    ButtonbtnFillGridFill Grid
    DataGriddataGrid1

  4. Copy and paste the following code into the top of Form1's Code window. Make sure that each namespace is referenced just once. System and System.Data may already be referenced by default.
    using System;
    using System.Data;
    using System.Data.SqlClient;
    					
  5. Copy and paste the following code at the top of public class Form1 to declare form-level variables for Form1:
    SqlDataAdapter da;
    DataSet ds;
    DataTable dtSource;
    int PageCount;
    int maxRec;
    int pageSize;
    int currentPage;
    int recNo;
    					
  6. Copy and paste the following code immediately after the static void Main method so that this code is form-level in scope:
    private void LoadPage() {
         int i;
         int startRec;
         int endRec;
         DataTable dtTemp;
    
         //Clone the source table to create a temporary table.
         dtTemp = dtSource.Clone();
    
         if (currentPage == PageCount) {
    	endRec = maxRec;
         }
         else {
    	endRec = pageSize * currentPage;
         }
         startRec = recNo;
    
         //Copy rows from the source table to fill the temporary table.
         for (i = startRec; i < endRec; i++) {
    	dtTemp.ImportRow(dtSource.Rows[i]);
    	recNo += 1;
         }
         dataGrid1.DataSource = dtTemp;
         DisplayPageInfo();
    }
    
    private void DisplayPageInfo() {
         txtDisplayPageNo.Text = "Page " + currentPage.ToString() + "/ " + PageCount.ToString();
    }
    
    private bool CheckFillButton() {
      // Check if the user clicks the "Fill Grid" button.
      if (pageSize == 0) {
         MessageBox.Show("Set the Page Size, and then click the Fill Grid button!");
         return false;
      }
      else {
         return true;
      }
    }
    					
  7. Paste the following code into the Form1_Load event procedure:
       //Open Connection. 
       SqlConnection conn = new SqlConnection("Server=server;uid=login;pwd=pwd;database=northwind");
    
       //Set the DataAdapter's query.
       da = new SqlDataAdapter("select * from customers", conn);
       ds = new DataSet();
    
       //Fill the DataSet.
       da.Fill(ds, "customers");
    
       //Set the source table.
       dtSource = ds.Tables["customers"];
    					
  8. Modify the connection string, which appears in the preceding code, as appropriate for your environment:
    SqlConnection conn = new SqlConnection("Server=server;uid=login;pwd=pwd;database=northwind");
    					
  9. Double-click Fill Grid to open the code window for btnFillGrid. Copy and paste the following code into the btnFillGrid_Click event procedure:
        // Set the start and max records. 
        pageSize = Convert.ToInt32(txtPageSize.Text);
        maxRec = dtSource.Rows.Count;
        PageCount = maxRec / pageSize;
    
        //Adjust the page number if the last page contains a partial page.
        if ((maxRec % pageSize) > 0) {
    	   PageCount += 1;
        }
    
        // Initial seeings
        currentPage = 1;
        recNo = 0;
    
        // Display the content of the current page.
        LoadPage();
    					
  10. Double-click First Page to open the code window for btnFirstPage. Copy and paste the following code into the btnFirstPage_Click event procedure:
       if (CheckFillButton() == false) {
         return;
       }
    
       //Check if you are already at the first page.
       if (currentPage == 1) {
           MessageBox.Show("You are at the First Page!");
           return;
       }
    
       currentPage = 1;
       recNo = 0;
       LoadPage();
    					
  11. Double-click Next Page to open the code window for btnNextPage. Copy and paste the following code into the btnNextPage_Click event procedure:
       //If the user did not click the "Fill Grid" button, then return.
       if (CheckFillButton() == false) { 
          return;
       }
    
       //Check if the user clicks the "Fill Grid" button.
       if (pageSize == 0) {
         MessageBox.Show("Set the Page Size, and then click the Fill Grid button!");
         return;
       }
    
       currentPage += 1;
       if (currentPage > PageCount) {
           currentPage = PageCount;
           //Check if you are already at the last page.
           if (recNo == maxRec) {
               MessageBox.Show("You are at the Last Page!");
      	   return;
           }
       }
       LoadPage();
    					
  12. Double-click Previous Page to open the code window for btnPreviousPage. Copy and paste the following code into the btnPreviousPage_Click event procedure:
       if (CheckFillButton() == false) {
          return;
       }
    
       if (currentPage == PageCount) {
          recNo = pageSize * (currentPage - 2);
       }
    
       currentPage -= 1;
       //Check if you are already at the first page.
       if (currentPage < 1) {
          MessageBox.Show("You are at the First Page!");
          currentPage = 1;
          return;
       }
       else {
          recNo = pageSize * (currentPage - 1);
       }
       LoadPage();
    					
  13. Double-click Last Page to open the code window for btnLastPage. Copy and paste the following code into the btnLastPage_Click event procedure:
       if (CheckFillButton() == false) {
          return;
       }
    
       //Check if you are already at the last page.
       if (recNo == maxRec) {
          MessageBox.Show("You are at the Last Page!");
          return;
       }
       currentPage = PageCount;
       recNo = pageSize * (currentPage - 1);
       LoadPage();
    					
  14. Press the F5 key to build and run the project.
  15. By default, the Page Size is set to 5 records. You can change this in the text box.
  16. Click Fill Grid. Notice that the DataGrid is filled with 5 records.
  17. Click First Page, Next Page, Previous Page, and Last Page to browse between pages.

Troubleshooting

  • This technique only works for read-only DataGrid controls. When you import a row to a temporary DataTable object, you make a copy. Thus, changes that you make are not saved to the main table.
  • This technique does not work (and neither does a collection or an array) if you want the user to be able to navigate to child records through a DataRelation object or if you have records that are linked in a parent-child relation that appear on the form at the same time.

REFERENCES

For more information about ADO.NET, refer to the following MSDN Web site:
Accessing Data with ADO.NET
http://msdn2.microsoft.com/en-us/library/e80y5yhx(vs.71).aspx
For more information, refer to the Microsoft .NET Framework SDK documentation:
.NET Framework SDK
http://msdn2.microsoft.com/en-us/library/aa719465(VS.71).aspx

Properties

Article ID: 307710 - Last Review: May 13, 2007 - Revision: 4.4
APPLIES TO
  • Microsoft ADO.NET 1.1
  • Microsoft ADO.NET 1.0
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords: 
kbhowtomaster kbsqlclient kbsystemdata KB307710

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com