<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:DataList ID="DataList1" runat="server" RepeatColumns = "2">
<ItemTemplate>
<table border = "1">
<tr>
<td id = "CheckBoxCell" runat = "server"><asp:CheckBox ID="CheckBox1" runat="server" /></td>
<td style = "width:150px"><b>Coupon: </b><asp:Label ID="lblCoupon" runat="server" Text='<%# Eval("Coupon") %>'></asp:Label></td>
<td style = "width:100px"><b>Code: </b><asp:Label ID="lblCode" runat="server" Text='<%# Eval("Code") %>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<br />
<asp:Button ID="Button1" runat="server" Text="Print" OnClick = "Print_DataList" />
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataList1.DataSource = GetData() ;
DataList1.DataBind();
}
}
private DataTable GetData()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Coupon"), new DataColumn("Code") });
dt.Rows.Add("Shirt", 199);
dt.Rows.Add("Football", 020);
dt.Rows.Add("Shirt", 566);
dt.Rows.Add("Disc", 099);
dt.Rows.Add("Watch", 54);
dt.Rows.Add("Clock", 890);
return dt;
}
protected void Print_DataList(object sender, EventArgs e)
{
DataTable dt = GetData();
List<DataRow> rows = new List<DataRow>();
foreach (DataListItem item in DataList1.Items)
{
if (!(item.FindControl("CheckBox1") as CheckBox).Checked)
{
rows.Add(dt.Rows[item.ItemIndex]);
}
}
foreach (DataRow row in rows)
{
dt.Rows.Remove(row);
}
DataList1.DataSource = dt;
DataList1.DataBind();
foreach (DataListItem item in DataList1.Items)
{
item.FindControl("CheckBoxCell").Visible = false;
}
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
DataList1.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("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());
}