AspnetO

We code, that works!

  • Home
  • Asp.net
  • MVC
  • Interview Questions
You are here: Home / Asp.net / How to Print Asp.net GridView Data on Button Click using Javascript?

How to Print Asp.net GridView Data on Button Click using Javascript?

By: Mayank Modi | Falls In: Asp.net, C#, VB | Last Updated: Oct 10, 2020

In my previous tutorials, I’d explained how to send gridview in email body, difference between String and string, check or uncheck all checkboxes in gridview and other more cracking tutorials on GridView, Asp.net, JavaScript, jQuery here.

Now here in this tutorial, I’ll explain how you can print asp.net gridview with its data when clicking on print button from code-behind using c# or vb.net and from client-side using javascript or jquery in asp.net.

Function to Print Asp.net Gridview – [JavaScript]

Following is the JavaScript function that is used to print asp.net gridview:

<script type=”text/javascript”>
function printGrid() {
var gridData = document.getElementById(‘<%= grdResultDetails.ClientID %>‘);
var windowUrl = ‘about:blank’;//set print document name for gridview
var uniqueName = new Date();
var windowName = ‘Print_’ + uniqueName.getTime();

var prtWindow = window.open(windowUrl, windowName,
‘left=100,top=100,right=100,bottom=100,width=700,height=500’);
prtWindow.document.write(‘<html><head></head>’);
prtWindow.document.write(‘<body style=”background:none !important”>’);
prtWindow.document.write(gridData.outerHTML);
prtWindow.document.write(‘</body></html>’);
prtWindow.document.close();
prtWindow.focus();
prtWindow.print();
prtWindow.close();
}
</script>

To call the above function on button click, add OnClientClick=”printGrid()” client-side event as shown below:

<asp:Button ID=”btnPrint” runat=”server” Text=”Print From Client-side” OnClientClick=”printGrid()” />

To call the above function on button click, add OnClick=”btnPrintFromCodeBehind_Click” server-side event as shown below:

<asp:Button ID=”btnPrintFromCodeBehind” runat=”server” Text=”Print From Code-behind”
OnClick=”btnPrintFromCodeBehind_Click” />

HTML Markup – [.aspx]

Following is the complete HTML markup for your .aspx page:

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
<title>Print asp.net gridview data using javascript</title>
<script type=”text/javascript”>
function printGrid() {
var gridData = document.getElementById(‘<%= grdResultDetails.ClientID %>‘);
var windowUrl = ‘about:blank’;//set print document name for gridview
var uniqueName = new Date();
var windowName = ‘Print_’ + uniqueName.getTime();

var prtWindow = window.open(windowUrl, windowName,
‘left=100,top=100,right=100,bottom=100,width=700,height=500’);
prtWindow.document.write(‘<html><head></head>’);
prtWindow.document.write(‘<body style=”background:none !important”>’);
prtWindow.document.write(gridData.outerHTML);
prtWindow.document.write(‘</body></html>’);
prtWindow.document.close();
prtWindow.focus();
prtWindow.print();
prtWindow.close();
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<table>
<tr>
<td><h4>Print asp.net gridview data in asp.net c#, vb.net</h4></td>
</tr>
<tr>
<td>
<asp:Button ID=”btnPrint” runat=”server” Text=”Print From Client-side”
OnClientClick=”printGrid()” />&nbsp;&nbsp;
<asp:Button ID=”btnPrintFromCodeBehind” runat=”server”
Text=”Print From Code-behind” OnClick=”btnPrintFromCodeBehind_Click” />
</td>
</tr>
<tr><td>&nbsp;&nbsp;</td></tr>
<tr>
<td>
<asp:GridView ID=”grdResultDetails” runat=”server” AutoGenerateColumns=”false”>
<HeaderStyle Font-Bold=”true” BackColor=”#ff6600″ BorderColor=”#222″
ForeColor=”White” Height=”30″ />
<Columns>
<asp:BoundField DataField=”Subjects” HeaderText=”Subjects” ItemStyle-Width=”150″
ItemStyle-HorizontalAlign=”Center” />
<asp:BoundField DataField=”Marks” HeaderText=”Marks” ItemStyle-Width=”150″
ItemStyle-HorizontalAlign=”Center” />
<asp:BoundField DataField=”Grade” HeaderText=”Grade” ItemStyle-Width=”150″
ItemStyle-HorizontalAlign=”Center” />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Code-behind – [C#]

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGridData();
}
}private void LoadGridData()
{
try
{
System.Data.DataTable dtSubData = new System.Data.DataTable();

//Creating grid columns
dtSubData.Columns.Add(“Subjects”);
dtSubData.Columns.Add(“Marks”);
dtSubData.Columns.Add(“Grade”);

//Adding row deails
dtSubData.Rows.Add(“Asp.net”, “70”, “B+”);
dtSubData.Rows.Add(“C#”, “80”, “A”);
dtSubData.Rows.Add(“Vb.net”, “76”, “A”);
dtSubData.Rows.Add(“HTML”, “91”, “A+”);
dtSubData.Rows.Add(“CSS”, “95”, “A+”);
dtSubData.Rows.Add(“JavaScript”, “78”, “A”);
dtSubData.Rows.Add(“jQuery”, “74”, “A”);

//Binding details to gridview
grdResultDetails.DataSource = dtSubData;
grdResultDetails.DataBind();
}
catch { }
}

protected void btnPrintFromCodeBehind_Click(object sender, EventArgs e)
{
try
{
ScriptManager.RegisterStartupScript(this, typeof(Page), “printGrid”, “printGrid();”, true);
}
catch { }
}

Code-behind – [Vb.net]

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGridData()
End If
End SubPrivate Sub LoadGridData()
Try
Dim dtSubData As New System.Data.DataTable()

‘Creating grid columns
dtSubData.Columns.Add(“Subjects”)
dtSubData.Columns.Add(“Marks”)
dtSubData.Columns.Add(“Grade”)

‘Adding row deails
dtSubData.Rows.Add(“Asp.net”, “70”, “B+”)
dtSubData.Rows.Add(“C#”, “80”, “A”)
dtSubData.Rows.Add(“Vb.net”, “76”, “A”)
dtSubData.Rows.Add(“HTML”, “91”, “A+”)
dtSubData.Rows.Add(“CSS”, “95”, “A+”)
dtSubData.Rows.Add(“JavaScript”, “78”, “A”)
dtSubData.Rows.Add(“jQuery”, “74”, “A”)

‘Binding details to gridview
grdResultDetails.DataSource = dtSubData
grdResultDetails.DataBind()
Catch
End Try
End Sub

Protected Sub btnPrintFromCodeBehind_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
ScriptManager.RegisterStartupScript(Me, GetType(Page), “printGrid”, “printGrid();”, True)
Catch
End Try
End Sub

Example Result

How to print asp.net gridview data on button click using javascript

Download Example

Icon

Print asp.net gridview data on button click using javascript

1 file(s) 29.57 KB
Download This Example

Signup Today And Get Latest Tutorials For Free!

Subscribe to us and get free latest tutorials notifications whenever we publish a new contents.

<

About Mayank Modi

Mayank is a web developer and designer who specializes in back-end as well as front-end development. He's a Founder & Chief Editor of AspnetO. If you'd like to connect with him, follow him on Twitter as @immayankmodi.

Comments

  1. Allan says

    Jun 18, 2015 at 10:06 PM

    Mayank, I tried your code for print gridView but I got a problem with paging. My grid view using paging, which makes the content displayed in multiple pages. Your codes only print first page. Any solution to print all?
    Thanks.

    Reply
    • Mayank Modi says

      Jun 21, 2015 at 9:38 PM

      This works for single page only without paging. If you want to print all data, you should first do an AJAX call that will make paging false to target GridView, then continue exporting process. If you want this functionality from server side, follow this https://www.aspneto.com/export-gridview-data-to-word-excel-text-pdf-file-asp-net-c-vb.html tutorial.

      Reply
  2. Jairo Rojas says

    Mar 29, 2015 at 9:22 PM

    Hi, all your article are pretty interesting now i got a question, dont u have a snipet code of how to print a form into PDF exactly the way it looks in html??
    Thanks in advance

    Reply
    • Mayank Modi says

      Mar 30, 2015 at 6:17 PM

      Hi Jairo,

      Thanks. Can you elaborate which form you are talking about?

      Reply

Leave a Reply Cancel reply

Search Your Topic



Social Connections

  • 1,438 Fans
  • 3,098 Followers
  • 51 Followers
  • 1,559 Subscribers

Get Latest Tutorials For Free



Top Posts

  • CSS3 Transition: fadeIn and fadeOut like Effects to Hide Show Elements
  • Top 10 OOPS Concepts In C# .NET With Examples
  • Show Confirm Message Box from Code-behind in Asp.net
  • Call JavaScript Function from Code-behind in Asp.net C# Vb
  • Pass Multiple Parameters in Asp.net QueryString Example

Contribute to AspnetO

If you want to contribute your unique blog articles or tutorials (Free / Paid) to AspnetO in any languages, you're most welcome. Just send me your previous articles, and topics on which you are interested to post an tutorial. Contact us at email listed in contact us page. Selected candidates will be contacted.

Search by Tags

Ado.net Ajax appSettings Asp.net C# CheckBox CheckBoxList ConnectionStrings Control CSS CSS3 Difference Download DropDownList Export Facebook fadeIn fadeOut fadeTo fadeToggle File File Extension FileUpload Function GridView IIS Interview Questions JavaScript jQuery MVC OOP RadioButtonList RDP Repeater Send Mail Solutions Split SQL Stored Procedure TextBox Upload Validation VB Web.config Web Hosting

The Man Behind AspnetO

Mayank Modi

Hi there,

Myself Mayank Modi, a Full Stack Developer (.NET Stack) and a blogger from Surat, India.

I'm welcoming you to my blog - AspnetO, a programmers community blog where we code, that works!

I started AspnetO as a hobby and now we're growing day by day. We're now having 5000+ programmers that get benefits and learn new things about website design and development under our community blog.

Here at AspnetO, I write about Beginners to Advance level of tutorials on programming languages like Asp.net using C# and Vb.net, MVC, SQL Server, JavaScript, jQuery etc. In sort, all about .NET Framework and website development stuff and sometimes sharing tips and tricks that can help you to grow up your programming skills.

You can get more details about me and my blog at About us page.

Subscribe To Newsletter

Enter your email address to subscribe to this blog and receive notifications of new posts right to your inbox

Join 1000+ other subscribers

<

Recent Posts

  • Main Difference between SessionState and ViewState in Asp.net
  • How to Get appSettings Value from Web.config File?
  • How to Get ConnectionString from Web.config in Asp.net?
  • Difference between appSettings and connectionStrings in Web.config
  • Get Folder Files List and Export to CSV in .NET
  • Get Files List From Directory Recursively in C# Vb.net
  • Get Hash Value From Current Page URL In jQuery
  • Handle Multiple Submit Buttons in Single MVC Form

Copyright © 2014 - 2021 · All Rights Reserved.

About | Copyrights | Privacy | Terms | Contact | Advertise | Sitemap
Previous What is the difference between String and string in Asp.net C#?
Next What is the difference between String and StringBuilder in Asp.net C# Vb.net?