Click here to Skip to main content
15,885,546 members
Articles / Web Development / ASP.NET / ASP.NET4.0
Tip/Trick

Print DataGridView data or particular control's data from web page

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
17 Jun 2013CPOL 8.3K   4  
This tip explains how to print a particular web control's data from a web page.

Introduction

This tip explains how to print a particular web control's data from a web page.

Background

I have tried to open a new page and use JavaScript to print the web page, but all the web page controls are printed using document.windows.print().

Using the code

JavaScript
<script>
function PrintCasedata() {
// var prtGrid1 = document.getElementById("<%= GridView1.ClientID %>");
var prtGrid1 = document.getElementById("<%= Panel1.ClientID %>");

// document.getElementById("GridView1");
//prtGrid1.border = 1;
var prtwin = window.open('', 'PrintCasedata', 
  'left=100,top=100,width=1000,height=1000,tollbar=0,scrollbars=1,status=0,resizable=1');
prtwin.document.write(prtGrid1.outerHTML);
prtwin.document.close();
prtwin.focus();
prtwin.print();
prtwin.close();
}
</script>

On this button I have added code tp print the DataGridView.

XML
<asp:Button ID="btnPrint" runat="server" 
  OnClick="btnPrint_Click" Text="Print" 
  Height="26px" Width="42px" />

Use the following code at codebehind:

C#
protected void btnPrint_Click(object sender, EventArgs e)
{
  //ScriptManager.RegisterStartupScript(this,
  //      this.GetType(), "mymessage", "Myprint(" + ");", true);
  ScriptManager.RegisterStartupScript(this, this.GetType(),
          "mymessage", "PrintCasedata(" + ");", true);
}

Using this code we can print the formatted web page,  i.e. we want the logo on the print, the date, and user name. So we need to collect all controls which need to print on one panel or group box. And then replace the id in GroupControlID.

JavaScript
var prtGrid1 = document.getElementById("<%= GroupControlID.ClientID %>");

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer MogyaSoft
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --