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
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
01
protected
void
Page_Load(
object
sender, EventArgs e)
02
{
03
string
printScript =
04
@"function PrintGridView()
05
{
06
var gridInsideDiv = document.getElementById('gvDiv');
07
var printWindow = window.open('gview.htm','PrintWindow','letf=0,top=0,width=150,height=300,toolbar=1,scrollbars=1,status=1');
08
printWindow.document.write(gridInsideDiv.innerHTML);
09
printWindow.document.close();
10
printWindow.focus();
11
printWindow.print();
12
printWindow.close();}"
;
13
this
.ClientScript.RegisterStartupScript(Page.GetType(),
"PrintGridView"
, printScript.ToString(),
true
);
14
btnPrint.Attributes.Add(
"onclick"
,
"PrintGridView();"
);
15
}
VB.NET
01
Protected
Sub
Page_Load(sender
As
Object
, e
As
EventArgs)
02
Dim
printScript
As
String
= "function PrintGridView()
03
{
04
var gridInsideDiv = document.getElementById(
'gvDiv');
05
var printWindow = window.open(
'gv.htm','PrintWindow','letf=0,top=0,width=150,height=300,toolbar=1,scrollbars=1,status=1');
06
printWindow.document.write(gridInsideDiv.innerHTML);
07
printWindow.document.close();
08
printWindow.focus();
09
printWindow.print();
10
printWindow.close();}"
11
Me
.ClientScript.RegisterStartupScript(Page.[
GetType
](),
"PrintGridView"
, printScript.ToString(),
True
)
12
btnPrint.Attributes.Add(
"onclick"
,
"PrintGridView();"
)
13
End
Sub
No comments:
Post a Comment