Print GridView Data Using JavaScript in Asp.Net
Hi guys, here i will explain how to print gridview data using javascript in asp.net.First of all we will get some data from SQL-Server to fill the gridview.Then we will take one Button, on Client Click event of the button we will call javascript function.
Design View:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>GridView Print With Javascript</title> <style type="text/css"> .auto-style1 { width: 1000%; background-color: #C0C0C0; } </style> <script type="text/javascript"> function PrintGridView() { var PGrid = document.getElementById('<%=GridView1.ClientID %>'); PGrid.border = 0; var Pwin = window.open('', 'PrintGrid', 'left=100,top=100,width=1024,height=768,tollbar=0,scrollbars=1,status=0,resizable=1'); Pwin.document.write(PGrid.outerHTML); Pwin.document.close(); Pwin.focus(); Pwin.print(); Pwin.close(); } </script> </head> <body> <form id="form1" runat="server"> <div> <table align="center" class="auto-style1"> <tr> <td> <asp:GridView ID="GridView1" runat="server"></asp:GridView> </td> </tr> <tr> <td> <asp:Button ID="Print" runat="server" OnClientClick="PrintGridView()" Text="Print" /> </td> </tr> </table> </div> </form> </body> </html>
Code View:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data.SqlClient; using System.Data; public partial class _Default : System.Web.UI.Page { String strconn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { binddata(); } } public void binddata() { SqlConnection con = new SqlConnection(strconn); con.Open(); SqlCommand cmd = new SqlCommand("select * from dept",con); SqlDataReader dr = cmd.ExecuteReader(); GridView1.DataSource = dr; GridView1.DataBind(); con.Close(); } }