Create a Printer friendly page for DataGrid


For one of my projects, user needed a feature where they could print out their search results (shown in a datagrid). The following steps builds a printer-friendly page for datagrid results.

1. Add a new aspx page, call it Print.aspx
2. Add javascript to trigger IE print, on body load,


--body onLoad= "self.print()" --

--body--

3. Now comes the data, pass the underlying datasource for the grid to this page (use the method you like, use a session variable (bad), use a unique keyed cache item (ok), get it from parents property (good). Once you have this data, the following code block does the trick. Key is the RenderControl method of datagrid. It uses a HtmlTextWriter object to write out the HTML snippet of the grid. If we create the grid with plain vanila settings for color and edges, it will be “printer friendly”.

On Page load add (don’t forget to pass the dataview,

Response.Write(CreatePrinterFriendlyPage(dview).toString());


private StringBuilder CreatePrinterFriendlyPage(DataView dv)
{

DataGrid dg = new DataGrid();
dg.DataSource = dv;
dg.HeaderStyle.Font.Name = "Arial";
dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.Font.Size = FontUnit.XSmall;
dg.ItemStyle.Font.Name = "Arial";
dg.ItemStyle.Font.Size = FontUnit.XXSmall;
dg.DataBind();

System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
dg.RenderControl(hw);

StringBuilder sb = new StringBuilder();
sb.Append (tw.ToString().Replace("\"","'").Replace("\r","").Replace("\n","").Replace("\t",""));

return (sb);

}

Happy coding !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s