Click here to Skip to main content
15,898,035 members
Articles / Web Development / ASP.NET

Print DataGrid of multiple columns on separate pages

Rate me:
Please Sign up or sign in to vote.
2.86/5 (7 votes)
13 Feb 2006CPOL3 min read 46.3K   23   1
This is an enhanced DataGrid having a print ability of multiple columns on separate pages.

Introduction

This is an enhanced DataGrid which has the ability to print multiple columns on separate pages.

Background

This control was created out of frustration, due to the fact that whenever a DataGrid was being rendered from a certain data source having multiple columns, the print wouldn't be able to display all the contents on a single page.

In order to print the current page, I used a printer friendly version of the data that needed to be displayed. However, as the columns in the page were increasing to any limit, I decided to recursively create the table, then bind the DataGrid to the data retrieved, and furthermore render the controls that needed to be displayed.

Code

I won't be attaching the source code to this article, as the code snippets that will be provided will be enough to get in a walkthrough.

Step 1:

Create a StringWriter and an HtmlTextWriter to render the control onto the page.

C#
// Initialize the variables
System.IO.StringWriter oStringWriter;
System.Web.UI.HtmlTextWriter oHtmlTextWriter;

try{
    // Create new instances
    oStringWriter =  new System.IO.StringWriter();
    oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);}
catch(Exception ex){
    Response.Write(ex.Message);
}

Step 2:

Obtain a meager amount of data (say, a DataTable having 6 or less number of columns) from your data access layer and bind the data to a runtime created DataGrid.

C#
// Initialize the variables
System.IO.StringWriter oStringWriter;System.Web.UI.HtmlTextWriter oHtmlTextWriter; 

try{ 
    for (int counter = 0; counter < numberOfPages; counter++) 
    { 
        // Create new instances  oStringWriter =  new System.IO.StringWriter();   
        oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); 
        sourceGrid = new DataGrid(); 
        // Get some source data having say 6 columns 
        sourceGrid.DataSource = GetSourceData(counter);
        sourceGrid.DataBind();  // Bind the grid 
    }
}
catch(Exception ex){ 
    Response.Write(ex.Message);
}

Note: GetSourceData() is a method that gets 6 columns from the Data Access Layer.

This method passes a parameter called page number which represents the current page that needs to be printed. In this case, the entire resultset needs to be retrieved in order to find out the number of columns present. Thereafter, the columns are divided into a page size of 6 and the resultant data will be printed onto the page.

In order to signify that the current page DataGrid needs to be printed at the start of each page, an attribute needs to be added to the STYLE of the DIV tag: "page-break-after :always;". A <DIV> tag in HTML will be created as a Generic control in C# using a System.Web.UI.HtmlControls.HtmlGenericControl.

Step 3:

Render the control onto the HTML writer and add the resultant string to the DIV tag.

Add the DIV contents to a Placeholder, which needs to be declared at the page level.

C#
// Create new instances
oStringWriter =  new System.IO.StringWriter();
oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); 
  
sourceGrid = new DataGrid();
// Get some source data having say 6 columns
sourceGrid.DataSource = GetSourceData(counter);
sourceGrid.DataBind();  // Bind the grid
sourceGrid.RenderControl(oHtmlTextWriter); 
HtmlGenericControl currentDIV = new HtmlGenericControl("DIV"); 
currentDIV.Attributes.Add("style", "page-break-after : always;");
currentDIV.InnerHtml = oStringWriter.ToString(); 
PlaceHolder1.Controls.Add(currentDIV);

Note: This DIV control needs to be created so that its contents will be hidden when viewed on the page, and just before the print data will be spooled to the printer, the <DIV> contents need to be sent to the printer. Once the print data has been spooled to the printer, the <DIV> contents are again kept hidden.

All this processing of hid/unhide of <DIV> controls are done at the client-end using JavaScript.

In the "Body" tag, use the "onbeforeprint" and "onafterprint" standard methods to hide/show the <DIV> tag.

HTML
<body MS_POSITIONING="GridLayout" onbeforeprint="BeforePrint();" onafterprint="AfterPrint();">

Add the JavaScript methods for Before Print and After Print:

JavaScript
<script language='javascript'>
function BeforePrint()
{
    var divEle  = document.getElementById("NewDiv");
    if (divEle  != null)
    {
        divEle.style.display = "";
    }
}
 
function AfterPrint()
{
    var divEle  = document.getElementById("NewDiv");
    if (divEle  != null)
    {
        divEle.style.display = "none";
    }
}</script>

Add the "NewDiv" element between the PlaceHolder variable.

HTML
<div id="NewDiv" style="display: NONE;">
    <asp:PlaceHolder id="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>

Step 4:

Print the page using the commonly used function: javascript:window.print().

JavaScript
btnPrint.Attributes.Add("onclick", "javascript:window.print();");

Conclusion

I hope this was of some use to you guys. I tried to make it as simple as possible for reusability - as I'm a strong believer of reusing code fragments.

License

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


Written By
India India
I'm a software engineer, working on various projects since a long time. Am working currently in .NET technology and have a great interest in the hacking world.

Comments and Discussions

 
QuestionHow to print all pages of a web datagrid in ASP.Net on a single click Pin
Haresh Vachhani11-Dec-06 22:23
Haresh Vachhani11-Dec-06 22:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.