<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID = "CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnPrint" runat="server" Text="Print"
onclick="btnPrint_Click" />
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void btnPrint_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
row.Visible = (row.FindControl("CheckBox1") as CheckBox).Checked;
}
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
string html = 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("if(printWin == null) return;");
sb.Append("printWin.document.write(\"");
sb.Append(html);
sb.Append("\");");
sb.Append("printWin.document.close();");
sb.Append("printWin.focus();");
sb.Append("printWin.print();printWin.opener.location.href=printWin.opener.location.href;");
sb.Append("printWin.close();};");
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
using System.Data;
using System.Text;
using System.IO;