<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
</Columns>
</asp:GridView>
<asp:Button ID="btnPrint" runat="server" Text="Print" OnClick = "Print" />
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Age") });
dt.Rows.Add("John", "12");
dt.Rows.Add("Sam", "42");
dt.Rows.Add("Mike", "31");
dt.Rows.Add("Jerry", "19");
dt.Rows.Add("Thomas", "77");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/*Verifies that the control is rendered */
}
protected void Print(object sender, EventArgs e)
{
GridView1.Attributes["style"] = "border-collapse:separate";
GridView1.HeaderRow.Visible = false;
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Cells[0].Visible = false;
if ((row.FindControl("CheckBox1") as CheckBox).Checked)
{
row.Attributes["style"] = "page-break-after:always;";
}
else
{
row.Visible = false;
}
}
}
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
string gridHTML = sw.ToString().Replace("\"", "'").Replace(System.Environment.NewLine, "");
StringBuilder sb = new StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload = new function(){");
sb.Append("var printWin = window.open('', '', 'left=0");
sb.Append(",top=0,width=1000,height=600,status=0');");
sb.Append("printWin.document.write(\"");
string style = "<style type = 'text/css'>thead {display:table-header-group;} tfoot{display:table-footer-group;}</style>";
sb.Append(style + gridHTML);
sb.Append("\");");
sb.Append("printWin.document.close();");
sb.Append("printWin.focus();");
sb.Append("printWin.print();");
sb.Append("printWin.close();");
sb.Append("};");
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());
GridView1.DataBind();
}