Categories
Asp, Asp.net

How To Print GridView in Asp.Net

How To Print GridView in Asp.Net

In this post we will learn How To Print GridView in Asp.Net. This feature come to handy for reporting purpose. Earlier we had discussed CRUD Operations Using Entity Framework in ASP.NET MVC. Here we are using JavaScript to accomplish this. We have used AdvetureWorks Database to fill GridView.

Design: 

<%@ 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>How To Print GridView in Asp.Net</title>
<style type="text/css">
body {
width: 980px;
margin: 0px auto;
text-align: center;
padding-top: 50px;
font-size: 20px;
}
</style>
<script type="text/javascript">
    function PrintGrid() {
    var pGrid = document.getElementById('<%=gv.ClientID %>');
    pGrid.border = 0;
    var pwin = window.open('', 'PrintGridViewData', 'left=100,top=100,width=1000,height=1000,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>
<h1>How To Print GridView in Asp.Net</h1>   
<asp:GridView ID="gv" runat="server" AllowPaging="true" PageSize="5" ShowFooter="true" AutoGenerateColumns="false" 
    Width="100%" DataSourceID="sdsrc" OnRowDataBound="gv_RowDataBound">

<Columns>
<asp:BoundField DataField="ProductID" HeaderText="Product ID" />
<asp:BoundField DataField="PurchaseOrderDetailID" HeaderText="Purchase Order ID" />
<asp:TemplateField HeaderText="Order Quantity">
<ItemTemplate>
<asp:Label ID="lblOrderQty" runat="server" Text='<%#Eval("OrderQty") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltxtTotal" runat="server" Text="Total Price" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
     
<asp:SqlDataSource ID="sdsrc" runat="server" SelectCommand="select * from [AdventureWorks2008R2].[Purchasing].[PurchaseOrderDetail]" ConnectionString="<%$ ConnectionStrings:con %>">
</asp:SqlDataSource>

<br /><br />
<input type="button" onclick="PrintGrid()" value="Print" />
<br /><br />
All rights reserved by <a href="http://www.hightechnology.in">www.Hightechnology.in</a> |
Hosting partner <a href="http://www.grootstech.com" target="_blank">Grootstech</a>
</div>
</form>
</body>
</html>

Result:

How To Print GridView in Asp.Net

Comments are closed.