Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
17 Jun 2013 1  
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

<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.

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

Use the following code at codebehind:

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.

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here