HOW TO: Perform Paging with the DataGrid Windows Control by Using Visual J# .NET (320626)



The information in this article applies to:

  • Microsoft Visual J# .NET (2002)
  • Microsoft Visual J# .NET (2003)

This article was previously published under Q320626
For a Microsoft Visual Basic .NET version of this article, see 305271.
For a Microsoft Visual C# .NET version of this article, see 307710.

IN THIS TASK

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 use 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. See the Troubleshooting section for more information.

back to the top

Requirements

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

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 J# .NET Windows Application project.
  2. Add DataGrid control, and then set its ReadOnly property to True.
  3. Place the following additional controls on Form1, and set their properties as follows:
    ControlName PropertyText Property
    ButtonbtnFirstPageFirst Page
    ButtonbtnNextPageNext Page
    TextBoxtxtDisplayPageNo
    ButtonbtnPreviousPagePrevious Page
    ButtonbtnLastPageLast Page
    TextBoxtxtPageSize5
    ButtonbtnFillGridFill Grid
    DataGriddataGrid1

  4. In the Toolbox, click the Data tab.
  5. Double-click the SqlDataAdapter.
  6. Follow the instructions in the wizard.
  7. Right-click the SqlDataAdapter.
  8. Click to select Generate Data Set.
  9. Follow the instructions in the wizard.
  10. Open the properties for the SqlConnection. If you do not see the logon password after the user ID, type it.
  11. Paste the following code in the top of the Form1 Code window. Make sure that each namespace is referenced just one time. By default, System and System.Data may already be referenced.
    import System.*;
    					
  12. Paste the following code at the top of public class Form1 to declare form-level variables for Form1:
    DataTable dtSource;
    int PageCount;
    int maxRec;
    int pageSize;
    int currentPage;
    int recNo;
    					
  13. Paste the following code in the constructor for the form:
                // Standard Error Handling
                try
                {
                      // Get Data
                      dtSource = dataSet11.get_Tables ().get_Item("customers");   
                      // Fill the DataSet
                      sqlDataAdapter1.Fill (dataSet11, "customers");
                }
                catch (Exception error)
                {
                      // Display Error
                      MessageBox.Show ("Constructor failed with error: " + error);                       
                }
           
    					
  14. Paste the following code immediately after the static void Main method so that this code is form-level in scope:
          // Get Data
          private void LoadPage ()
          {
    
                // Local Declaration
                int loop,
                      start,
                      stop,
                      rows;
                DataTable dtTemp;
    
                // Standard Error Handling
                try
                {
    
                       // Initialize
                      rows = dtSource.get_Rows ().get_Count ();
                      dtTemp = dtSource.Clone ();
    
                      // Error Checking
                      if (rows < 1)
                      {
                            MessageBox.Show ("No Data to Show", "Empty Table");
                            return;
                      }
    
                      // Set Loop Values
                      if (currentPage == PageCount) stop = maxRec;
                      else stop = pageSize * currentPage;
                      start = recNo;
    
                      // Transfer Data to Temporary Table
                      for (loop = start; loop < stop; loop ++)
                      {
                            dtTemp.ImportRow (dtSource.get_Rows ().get_Item(loop));
                            recNo ++;
                      }
    
                      // Show Data
                      dataGrid1.set_DataSource (dtTemp);
                      DisplayPageInfo ();
    
                }
                catch (Exception error)
                {
                      MessageBox.Show ("LoadPage failed with error: " + error);
                }
    
          }
    
          // Output Data
          private void DisplayPageInfo() 
          {
                txtDisplayPageNo.set_Text ("Page " + currentPage + " / " + PageCount);
          }
    
          // Notify to Fill Data Grid
          private boolean 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;}
    
          }
    					
  15. Double-click the Fill Grid button to open the code window for btnFillGrid. Paste the following code in the btnFillGrid_Click event procedure:
                // Set the start and max records. 
                pageSize = Convert.ToInt32(txtPageSize.get_Text ());
                maxRec = dtSource.get_Rows ().get_Count ();
                PageCount = maxRec / pageSize;
    
                // Adjust the page number if the last page contains a partial   
                // page
                if ((maxRec % pageSize) > 0) PageCount ++;
    
                // Initial seeings
                currentPage = 1;
                recNo = 0;
    
                // Display the content of the current page.
                LoadPage();
    					
  16. Double-click the First Page button to open the code window for btnFirstPage. Paste the following code in the btnFirstPage_Click event procedure:
                // Verify Data
                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;
                }
    
                // Reset to First Page
                currentPage = 1;
                recNo = 0;
                LoadPage();
    					
  17. Double-click the Next Page button to open the code window for btnNextPage. Paste the following code in 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;
                }
     
                // Check if you are already at the last page.
                currentPage ++;
                if (currentPage > PageCount) 
                {
                      currentPage = PageCount;
                      if (recNo == maxRec) 
                      {
                            MessageBox.Show("You are at the Last Page!");
                            return;
                      }
    
                }
                LoadPage();
    					
  18. Double-click the Previous Page button to open the code window for btnPreviousPage. Paste the following code in the btnPreviousPage_Click event procedure:
                // Notify User
                if (CheckFillButton() == false) return;
    
                // Set Record Count
                if (currentPage == PageCount) 
                     recNo = pageSize * (currentPage - 2);
     
                //Check if you are already at the first page.
                currentPage --;
                if (currentPage < 1) 
                {
                      MessageBox.Show("You are at the First Page!");
                      currentPage = 1;
                      return;
                }
                else {recNo = pageSize * (currentPage - 1);}
                LoadPage();
    					
  19. Double-click the Last Page button to open the code window for btnLastPage. Paste the following code in the btnLastPage_Click event procedure:
                // Notify User
                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;
                }
     
                // Set Tracking
                currentPage = PageCount;
                recNo = pageSize * (currentPage - 1);
                LoadPage();
    					
  20. Press the F5 key to build and run the project.
  21. By default, the Page Size is set to 5 records. You can change this in the text box.
  22. Click Fill Grid. Notice that the DataGrid is filled with 5 records.
  23. Click First Page, Next Page, Previous Page, and Last Page to view these pages.
back to the top

Troubleshooting

  • This technique only works for read-only DataGrid controls. When you import a row to a temporary DataTable object, you make a copy. Therefore, 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 locate child records through a DataRelation object or if you have records that are linked in a parent-child relation and that appear on the form at the same time.
back to the top

REFERENCES

For more information about ADO.NET, see the following MSDN Web site: For more information, see the Microsoft .NET Framework SDK documentation: back to the top

Modification Type:MajorLast Reviewed:8/7/2003
Keywords:kbControl kbDataBinding kbHOWTOmaster KB320626 kbAudDeveloper