Click here to Skip to main content
15,881,852 members
Articles / Web Development / ASP.NET
Article

Printing datagrid columns using C# and javascript

Rate me:
Please Sign up or sign in to vote.
1.62/5 (6 votes)
1 Apr 20062 min read 53.7K   17   5
This article helps to print multiple columns of a table that do not fit in a single page

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


Written By
India India
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 Pin
redekar8-May-07 2:33
redekar8-May-07 2:33 
AnswerRe: can u give me sample project Pin
Soshan Fernandes9-May-07 17:27
Soshan Fernandes9-May-07 17:27 
Generalsource code Pin
7enah10-Mar-07 8:32
7enah10-Mar-07 8:32 
GeneralGreat Job Soshan... Pin
Satish N Kota10-Apr-06 5:11
Satish N Kota10-Apr-06 5:11 
Hi Shoshan,

Though this peice of code is not directly helped me...but it has helped me great on doing some other stuff which I wanted to and it solved my problem which I was worrying for past 2 days and wasted my weekends...

Kudos to you....!!!

Regards
Satish N Kota

Satish N Kota
Sr. Engineer,
Kitbag,
Merican Manners Industrial Estate,
ILKESTON,
DERBYSHIRE DE7 8EF
United Kingdom
GeneralRe: Great Job Soshan... Pin
Soshan Fernandes7-May-06 7:56
Soshan Fernandes7-May-06 7:56 

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.