Create a web form like below. Put all the controls inside one Panel.
On click event of the “Print Page” button write below code.
Use the below namespace
Create the function PrintWebControl which is calling from the click event of the “Page Print” button.
Done!!!! Execute it…Enjoy printing controls….
On click event of the “Print Page” button write below code.
1: //Write the below code for click event of the "Print Page" button
2: protected void btnPrintPage_Click(object sender,
EventArgs e)
3: {
4: Session["ctrl"] = Panel1;
5: Control ctrl = (Control)Session["ctrl"];
6: PrintWebControl(ctrl);
7: }
Use the below namespace
using System.IO;
Create the function PrintWebControl which is calling from the click event of the “Page Print” button.
1: public static void PrintWebControl(Control ControlToPrint)
2: {
3: StringWriter stringWrite = new StringWriter();
4: System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
5: if (ControlToPrint is WebControl)
6: {
7: Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ControlToPrint).Width = w;
8: }
9: Page pg = new Page();
10: pg.EnableEventValidation = false;
11: HtmlForm frm = new HtmlForm();
12: pg.Controls.Add(frm);
13: frm.Attributes.Add("runat", "server");
14: frm.Controls.Add(ControlToPrint);
15: pg.DesignerInitialize();
16: pg.RenderControl(htmlWrite);
17: string strHTML = stringWrite.ToString();
18: HttpContext.Current.Response.Clear();
19: HttpContext.Current.Response.Write(strHTML);
20: HttpContext.Current.Response.Write("<script>window.print();</script>");
21: HttpContext.Current.Response.End();
22: }
Done!!!! Execute it…Enjoy printing controls….