In this post, I will show you how to print Asp.net webform gridview.
Let’s consider the following example.
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
private DataTable GetDataTable()
{
//create table
DataTable dt = new DataTable("Product");
dt.Columns.Add("ProductID", Type.GetType("System.Int32"));
dt.Columns.Add("ProductName", Type.GetType("System.String"));
//create fields
DataColumn[] pk = new DataColumn[1];
pk[0] = dt.Columns["ProductID"];
dt.PrimaryKey = pk;
dt.Columns["ProductID"].AutoIncrement = true;
dt.Columns["ProductID"].AutoIncrementSeed = 1;
dt.Columns["ProductID"].ReadOnly = true;
//fill rows
DataRow dr;
for (int x = 1; x <= 10; x++)
{
//make every other one different
if (Math.IEEERemainder(x, 2) == 0)
{
dr = dt.NewRow();
dr["ProductName"] = "Riss";
dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr["ProductName"] = "Product";
dt.Rows.Add(dr);
}
}
return dt;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetDataTable();
GridView1.DataBind();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function CallPrint(strid)
{
var prtContent = document.getElementById(strid);
var WinPrint = window.open('','','letf=0,top=0,width=400,height=400,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="divPrint">
<asp:GridView ID="GridView1" runat="server" />
</div>
<input type="button" value="print " id="btnPrint" runat="Server" onclick="javascript:CallPrint('divPrint')" />
</form>
</body>
</html>
use html (<input type="button">) button instead of <asp:button>>.