5,445,109 members and growing! (13,958 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » General     Intermediate License: The Code Project Open License (CPOL)

Customising the DataGrid pager in ASP.NET

By Munsifali Rashid

Making the pager in a DataGrid more useful by adding additional information about the data being displayed.
C#.NET 1.1, WinXP, Windows, .NET, ADO.NET, ASP.NET, Visual Studio, VS.NET2003, Dev

Posted: 15 Oct 2005
Updated: 15 Oct 2005
Views: 40,452
Bookmarked: 28 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
15 votes for this Article.
Popularity: 5.25 Rating: 4.46 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
1 vote, 6.7%
3
5 votes, 33.3%
4
9 votes, 60.0%
5

Introduction

The built-in DataGrid control in ASP.NET is great for displaying tabular data. This article shows how we can extend this control and modify the pager to display some additional information about the data, such as number of records and number of pages.

Background

The pager in a DataGrid is helpful in allowing users to page through long lists of data. However, with the page numbers aligned to the right, we have a big empty space to the left which can be used more efficiently (See image 1). This article shows how we can insert some additional information about the data into this space - i.e. a text like: Displaying 82 records. Currently on page 2 of 10. We can also apply some optional formatting, removing the page numbers if there is only one page.

Image 1. The default DataGrid control.

The default datagrid with paging

Creating the extended datagrid control

To get started, we create a new class inheriting from the DataGrid. We name this new class DataGridWithImprovedPager.

class DataGridWithImprovedPager: DataGrid
{
  private bool m_DisplayPageNumbers = true;

  public DataGridWithImprovedPager()
  {
  }
}

We override the OnItemCreated method, and insert a blank label (and cell) into the pager. We will retrieve this label before the control is rendered and populate it with information about the data being displayed.

protected override void OnItemCreated(DataGridItemEventArgs e)
{
  switch (e.Item.ItemType)
  {
    case (ListItemType.Pager):

      // Only display paging links if we have more than one page

      m_DisplayPageNumbers = (this.PageCount > 1);

      // Get the table cell holding the page numbers

      TableCell cell = e.Item.Controls[0] as TableCell;

      // Hide the cell if we're not displaying page numbers

      cell.Visible = m_DisplayPageNumbers;
    
      // Check that we haven't added our numrecords label already

      // For some reason, the Pager item gets hit twice.

      if (cell.FindControl("lblNumRecords") == null)
      {
        // Work out how many columns we needs to substract from our colspan

        int count = (m_DisplayPageNumbers && this.Columns.Count > 1) ?
                     this.Columns.Count - 1 : this.Columns.Count;

        // Extract the Pager 

        TableCell pager = (TableCell) e.Item.Controls[0];

        // Add Cell to Row to Hold Row Count Label 

        TableCell newcell = new TableCell();
        newcell.ColumnSpan = count;
        newcell.HorizontalAlign = HorizontalAlign.Left;
        newcell.Style["border-color"] = pager.Style["border-color"];

        // Add Label Indicating Row Count 

        Label lblNumRecords = new Label();
        lblNumRecords.ID = "lblNumRecords";

        // Create a new column and append it to

        // the list if we have more the one column.

        // Otherwise, just add our label into the existing column

        if (this.Columns.Count > 1)
        {
          newcell.Controls.Add(lblNumRecords);

          // Add Table Cell to Pager 

          e.Item.Controls.AddAt(0, newcell);

          // Subtract from Colspan of Original Pager to Account for New Row 

          pager.ColumnSpan = pager.ColumnSpan - count;
        }
        else
        {
          cell.Controls.AddAt(0, lblNumRecords);
        }
      }

      break;
  }

  base.OnItemCreated (e);
}

The final step is to override the OnPreRender method, and retrieve the label we added previously. We then populate it with the number of items we have in the list, and if we have more than one page, then information about the current page and the total page count is also included.

protected override void OnPreRender(System.EventArgs e)
{
  Control c1 = this.Controls[0];
  Control c2 = c1.Controls[c1.Controls.Count - 1];
  Label lblNumRecords = c2.FindControl("lblNumRecords") as Label;

  // Populate the message label with the number of records

  lblNumRecords.Text = string.Format("{0} records found.", this.VirtualItemCount);

  // If we have pages of data, then update the message to show paging information

  if (m_DisplayPageNumbers)
  {
    lblNumRecords.Text += string.Format(" Currently on page {0} of {1}.",
                                          CurrentPageIndex+1,
                                          PageCount);
  }

  base.OnPreRender (e);
}

Image 2. Our improved DataGrid control.

Our improved datagrid with paging

Points of Interest

I had some trouble retrieving the total number of items in the list from within the DataGrid, so the VirtualItemCount property must be set manually from within the code when binding data.

History

This is my first article, and any suggestions or comments would be appreciated! :-)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Munsifali Rashid


I'm a freelance web developer with 7+ years experience developing solutions using Microsoft technologies.

Originally from London (UK) but now living in Orlando, FL, I'm currently working on various projects for numerous digital agencies across the globe, providing them with development and consulting services.

My website and blog are at http://www.mlogix-inc.com/
Occupation: Web Developer
Company: mLogix Inc
Location: United States United States

Other popular ASP.NET Controls articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 3 of 3 (Total in Forum: 3) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralGood Job Can You Populate Images in a Datagrid in te same waymembercoolnaveen123420:11 31 Mar '06  
GeneralWhat about cell width?membermiksh6:00 18 Oct '05  
GeneralGood jobmemberKeithPRC5:36 15 Oct '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 Oct 2005
Editor: Smitha Vijayan
Copyright 2005 by Munsifali Rashid
Everything else Copyright © CodeProject, 1999-2008
Web16 | Advertise on the Code Project