To Print GridView Data In Asp.Net Using C# And VB.NET, I have placed
GridView inside a Div and this Div will be called for printing using
javascript.
Print window will be opened in onclick event of Button. Javascript to print data is written in Page Load event of page and registered with RegisterStartupScript.
HTML SOURCE OF GRIDVIEW
C# CODE
VB.NET
Print window will be opened in onclick event of Button. Javascript to print data is written in Page Load event of page and registered with RegisterStartupScript.
HTML SOURCE OF GRIDVIEW
1: <div id="gvDiv">
2:
3: <asp:GridView ID="gvPrint" runat="server"
4: DataSourceID="SqlDataSource1">
5: <Columns>
6: <asp:BoundField DataField="CategoryID"
7: HeaderText="CategoryID"/>
8: <asp:BoundField DataField="CategoryName"
9: HeaderText="CategoryName"/>
10: </Columns>
11: </asp:GridView>
12: </div>
13:
14: <asp:Button ID="btnPrint" runat="server"
15: Text="Print Data"/>
C# CODE
protected void Page_Load(object sender, EventArgs e) { string printScript = @"function PrintGridView() { var gridInsideDiv = document.getElementById('gvDiv'); var printWindow = window.open('gview.htm','PrintWindow','letf=0,top=0,width=150,height=300,toolbar=1,scrollbars=1,status=1'); printWindow.document.write(gridInsideDiv.innerHTML); printWindow.document.close(); printWindow.focus(); printWindow.print(); printWindow.close();}"; this.ClientScript.RegisterStartupScript(Page.GetType(), "PrintGridView", printScript.ToString(), true); btnPrint.Attributes.Add("onclick", "PrintGridView();"); }
VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs) Dim printScript As String = "function PrintGridView() { var gridInsideDiv = document.getElementById('gvDiv'); var printWindow = window.open('gv.htm','PrintWindow','letf=0,top=0,width=150,height=300,toolbar=1,scrollbars=1,status=1'); printWindow.document.write(gridInsideDiv.innerHTML); printWindow.document.close(); printWindow.focus(); printWindow.print(); printWindow.close();}" Me.ClientScript.RegisterStartupScript(Page.[GetType](), "PrintGridView", printScript.ToString(), True) btnPrint.Attributes.Add("onclick", "PrintGridView();") End Sub
DataGridView printing in C#.NET
ReplyDeleteGridView printing event in C#
ReplyDeletePrint DataGridView using C# code
ReplyDelete