65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jun 17, 2013

CPOL
viewsIcon

8433

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 %>");