Tuesday, April 7, 2009

How to Print output of single asp.net control.

I Write Code in C# to print output of Single Control..
We Can Use this function for printing Grid,Table,Div etc Controls.
Importent thing here is tmpPage.RenderControl Method of Page object. Which Will Write HTML Exposed by Control in String Variable..Write it to response of Current Context
and then Use Window.print to print Response of the page.

public void PrintThis(Control ctrl)
{
StringWriter tmpStringWriter = new StringWriter();
System.Web.UI.HtmlTextWriter tmphtmlWrite = new System.Web.UI.HtmlTextWriter(tmpStringWriter);
//Declare Form
HtmlForm tmpform = new HtmlForm();
tmpform.Attributes.Add("runat", "server");
//Declare Page
Page tmpPage = new Page();
tmpPage.EnableEventValidation = false;
tmpPage.Controls.Add(tmpform);
//Add Form Control To Page
tmpform.Controls.Add(ctrl);
//Initialize page
tmpPage.DesignerInitialize();
//Render Page OutPut
tmpPage.RenderControl(tmphtmlWrite);
//Get Output string in String Varuable
string tmpstrHTML = tmpStringWriter.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(tmpstrHTML);
HttpContext.Current.Response.Write("<script>window.print();</script>
");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}


Hop this will help You.
Thanks..