Wednesday, 19 September 2018

Print Gridview from c#

Here are the Two events for Printing Gridview on Button Click Event. First One is for printing current page of Gridview and Second One is for printing all pages of Gridview. Here we are executing some Javascript to print Gridview after allowing or disallowing Gridview


protected void PrintCurrentPage(object sender, EventArgs e)
{
      GridView1.PagerSettings.Visible = false;
      GridView1.DataBind();
      StringWriter sw = new StringWriter();
      HtmlTextWriter hw = new HtmlTextWriter(sw);
      GridView1.RenderControl(hw);
      string gridHTML = sw.ToString().Replace("\"",   "'")
      .Replace(System.Environment.NewLine, "");           
      StringBuilder sb = new StringBuilder();
      sb.Append("<script type = 'text/javascript'>");
      sb.Append("window.onload = new function(){");
      sb.Append("var printWin = window.open('', '', 'left=0");
      sb.Append(",top=0,width=1000,height=600,status=0');");
      sb.Append("printWin.document.write(\"");
      sb.Append(gridHTML);
      sb.Append("\");");
      sb.Append("printWin.document.close();");
      sb.Append("printWin.focus();");
      sb.Append("printWin.print();");
      sb.Append("printWin.close();};");
      sb.Append("</script>");
      ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());
      GridView1.PagerSettings.Visible = true;
      GridView1.DataBind();
}


protected void PrintAllPages(object sender, EventArgs e)
{
      GridView1.AllowPaging = false;
      GridView1.DataBind();
      StringWriter sw = new StringWriter();
      HtmlTextWriter hw = new HtmlTextWriter(sw);
      GridView1.RenderControl(hw);
      string gridHTML = sw.ToString().Replace("\"", "'")
      .Replace(System.Environment.NewLine, "");
      StringBuilder sb = new StringBuilder();
      sb.Append("<script type = 'text/javascript'>");
      sb.Append("window.onload = new function(){");
      sb.Append("var printWin = window.open('', '', 'left=0");
      sb.Append(",top=0,width=1000,height=600,status=0');");
      sb.Append("printWin.document.write(\"");
      sb.Append(gridHTML);
      sb.Append("\");");
      sb.Append("printWin.document.close();");
      sb.Append("printWin.focus();");
      sb.Append("printWin.print();");
      sb.Append("printWin.close();};");
      sb.Append("</script>");
     ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());
     GridView1.AllowPaging = true;
     GridView1.DataBind();
}



Happy Coding !!!














No comments:

Post a Comment

SQL Audits

1. sys.server_audits What it is: Lists all server-level audit objects . An audit is the top-level object that defines: Where to wri...