Click here to Skip to main content
Click here to Skip to main content
Go to top

Printing datagrid columns using C# and javascript

, 1 Apr 2006
Rate this:
Please Sign up or sign in to vote.
This article helps to print multiple columns of a table that do not fit in a single page
<!-- Article Starts - DO NOT ADD HTML/BODY START TAGS-->

Introduction

This is an enhanced datagrid having a print ability of multiple columns on seperate pages.

Background

This control was created after out of frustration, due to the fact that whenever a datagrid was being rendered from a certain datasource having mutiple columns, the print wouldnt 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 string writer and an html writer to render the control onto the page.

// Initialize the variables  <PRE>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.

// Initialize the variables  <PRE>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();      sourceGrid.DataSource = GetSourceData(counter); // Get some source data having say 6 columns      sourceGrid.DataBind();  // Bind the grid     }
}
catch(Exception ex)
{ Response.Write(ex.Message); }

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

This method passes a parameter called page number which signifies the curent 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 to 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 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 the Placeholder, which need to be declared at the page level.

 // Create new instances    oStringWriter =  new System.IO.StringWriter();   oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);         sourceGrid = new DataGrid();   sourceGrid.DataSource = GetSourceData(counter); // Get some source data having say 6 columns   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 it's contents will be hidden when viewed on the page and just before the print data will be spooled to the printer, the <DIV> contents needs to be send to the printer. Once the print data has been spooled to the printer, the <DIV> contents are again kept hidden.

All this processing of HIDE/UNHIDE <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. 

Add the javscript methods for Before Print and After Print.
Add the "NewDiv" element between the placeholder variable.
<DIV><div id="NewDiv" style="display: NONE;">     <asp:PlaceHolder id="PlaceHolder1" runat="server"></asp:PlaceHolder>  </div></DIV>

 

Step 4:

Print the page using the commonly used function : _javascript:window.print();
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Soshan is a software engineer, currently working in variant projects. She does her programming in stuff like Assembler, C++, MFC and lots of web- and database stuff and now uses ASP.NET and C# extensively, too.
 
In her free time, she works in animation stuffs with extensive usage of Adobe Photoshop and CorelDraw. Driving racer cars is her current craze.
 
Whenever she gets bored, her interests goes on to networking and hacking-ethical. Has designed an ip-filter for firewall with a group of friends.

Comments and Discussions

 
Questioncan u give me sample project Pinmemberredekar8-May-07 2:33 
AnswerRe: can u give me sample project PinmemberSoshan Fernandes9-May-07 17:27 
Generalsource code Pinmember7enah10-Mar-07 8:32 
GeneralGreat Job Soshan... PinmemberSatish N Kota10-Apr-06 5:11 
GeneralRe: Great Job Soshan... PinmemberSoshan Fernandes7-May-06 7:56 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 1 Apr 2006
Article Copyright 2006 by Soshan Fernandes
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid