Click here to Skip to main content
5,790,650 members and growing! (18,256 online)
Email Password   helpLost your password?
Web Development » Custom Controls » General     Intermediate License: The Code Project Open License (CPOL)

Printing a GridView with Paging

By Cassio Mosqueira

This is a WebControl that provides an easy way to prepare an ASP.NET GridView to be paged and printed in the browser.
C#, Windows, .NET 2.0, .NET, WebForms, Visual Studio, ASP.NET, Dev

Posted: 16 Oct 2007
Updated: 18 Oct 2007
Views: 20,790
Bookmarked: 42 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
17 votes for this Article.
Popularity: 5.48 Rating: 4.46 out of 5
0 votes, 0.0%
1
1 vote, 5.9%
2
1 vote, 5.9%
3
1 vote, 5.9%
4
14 votes, 82.4%
5

Introduction

This is a WebControl that provides an easy way to prepare an ASP.NET GridView to be paged and printed in the browser.

How It Works

This control inherits from the regular GridView, so no original feature will be lost.
We implement the paging by overriding the method that renders the gridview row when we detect that it should be the last row in the current page. This is done by using the method SetRenderMethodDelegate of the row.

void ReportGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
    {
        _currentPageRow++;
        if (_currentPageRow == this._printPageSize)
        {
            _currentPageRow = 0;
            e.Row.SetRenderMethodDelegate(PageBreakRender);
        }
    }
}

Now, the last row of each page will use our PageBreakRender method to render itself. So, in the PageBreakRender method we have to manually render the contents of the row, that's where we are going to close the table, insert a page break and open the table again in the next page.
Here's the PageBreakRender method:

protected void PageBreakRender(HtmlTextWriter output, Control container)
{
    HtmlTextWriter cellsWriter = new HtmlTextWriter(new StringWriter());
    foreach (Control c in container.Controls)
    {
        TableCell cell = (TableCell)c;
        cell.RenderControl(cellsWriter);
    }

    output.Write("<tr>");
    output.Write(cellsWriter.InnerWriter.ToString());
    output.Write("</tr></table>");
    output.Write(GetPageFooterHtml());

    //If it is the last row, don't show the next header

    if (_currentPrintPage ==  PrintPageCount && Rows.Count % 
        (_currentPrintPage) == 0)
        return;

    output.Write("<div style=\"page-break-after:always;\"></div>");
    output.Write(GetHeaderHtml());
    _currentPrintPage++;
}

Note that there is a call to a method named GetHeaderHtml. This method returns the header of the GridView, so it can be rendered again in the new page.

This is the main idea behind the control. I also added the capability to render a custom page header and page footer defined in templates. Enabling the use of templates is very straight forward and you should find plenty of resources about it on the internet. You can also take a closer look at the source code to see how it works.

How To Use It

This control will work just like a regular GridView, but to enable paging we should look at a couple of properties:

  • AllowPrintPaging – Enables the paging (bool)
  • PrintPageSize - The number of rows that will fit in one single page (int)

The control's opening tag should be something like this:

<wc:ReportGridView runat="server" BorderWidth="1" 
    ID="gvSample" PrintPageSize="23" AllowPrintPaging="true" 
    AutoGenerateColumns="false">

That's it. Adding these two properties will make ASP.NET output several GridViews, one for each page.

You can still insert custom content between each GridView, before and after the page break. This can be accomplished by defining a PageHeaderTemplate and a PageFooterTemplate.

Here is the GridView used in our sample page:

<wc:ReportGridView runat="server" BorderWidth="1" 
    ID="gvSample" AutoGenerateColumns="false" PrintPageSize="23" 
    AllowPrintPaging="true"
            Width="600px">
        <Columns>
            <asp:BoundField DataField="Name" HeaderText="Customer Name" />
            <asp:BoundField DataField="PhoneNumber" 
                HeaderText="Customer Phone" 
                ItemStyle-HorizontalAlign="center" />
        </Columns>
        <PageHeaderTemplate>
            <br />
            PAGE HEADER TEMPLATE HERE
            <br />
        </PageHeaderTemplate>
        <PageFooterTemplate>
            <br />

            <hr />
            Page <%# gvSample.CurrentPrintPage.ToString() %> / 
                    <%# gvSample.PrintPageCount %>

        </PageFooterTemplate>
    </wc:ReportGridView>

Notice that there are a couple more properties that we can use in the templates:

  • CurrentPrintPage – Return the current page that is being rendered
  • PrintPageCount – The total number of pages

It can be used to display the page number at the footer or at the header of the page, as we can see in the sample picture above.

Known Issues

When using Firefox, the BorderWith property must be set explicitly. Otherwise the border of the GridView won't be displayed.

Conclusion

In this article, we saw how we can extend the GridView control to add custom rendering logic and provide a useful feature such as preparing it for printing in the browser.

License

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

About the Author

Cassio Mosqueira


I've been developing .NET enterprise applications since 2002.

I am originally from Rio de Janeiro and I am currently working as a developer for Sales Resource Group in Oakville, Ontario.

I'm vegetarian and I like surfing and listening to progressive metal bands like Dream Theater and Pain of Salvation.

Check out my blog!

Occupation: Web Developer
Location: Brazil Brazil

Other popular Custom 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
GeneralHeaderstyle - alignmentmemberkatem62:10 31 Jul '08  
GeneralRe: Headerstyle - alignmentmemberCassio Mosqueira4:10 31 Jul '08  
GeneralOne small fixmemberingridt12:44 19 Nov '07  

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

PermaLink | Privacy | Terms of Use
Last Updated: 18 Oct 2007
Editor: Sean Ewington
Copyright 2007 by Cassio Mosqueira
Everything else Copyright © CodeProject, 1999-2009
Web13 | Advertise on the Code Project