Sample:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%-- http://community.csdn.net/Expert/TopicView3.asp?id=5654641 --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
// 首次加载数据一定要放在 !IsPostBack 内,
// 避免回发的时候再次绑定数据,覆盖复选框状态
LoadProductData();
}
}
void chk_CheckedChanged(object sender, EventArgs e)
{
// 触发此事件的 CheckBox
CheckBox chk = sender as CheckBox;
// 得到 CheckBox 所在行
RepeaterItem item = chk.NamingContainer as RepeaterItem;
// 得到 Repeater,当然这里可以直接引用控件ID
Repeater grd = item.NamingContainer as Repeater;
Label lblProductName = item.FindControl("lblProductName") as Label;
Response.Write(item.ItemIndex);
Response.Write(lblProductName.Text);
// 你自己的绑定代码
// more codes
// ...
}
void LoadProductData()
{
DataTable dt = CreateProductTable();
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
#region sample data
static DataTable CreateProductTable()
{
DataTable tbl = new DataTable("Products");
tbl.Columns.Add("ProductID", typeof(int));
tbl.Columns.Add("ProductName", typeof(string));
tbl.Columns.Add("CategoryID", typeof(int));
tbl.Columns.Add("HasPic", typeof(bool));
tbl.Columns.Add("Reviewed", typeof(bool));
DataRow row = tbl.NewRow();
row[0] = 1;
row[1] = "Chai";
row[2] = 1;
row[3] = true;
row[4] = false;
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = 2;
row[1] = "Chang";
row[2] = 1;
row[3] = false;
row[4] = false;
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = 3;
row[1] = "Aniseed Syrup";
row[2] = 2;
row[3] = true;
row[4] = false;
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = 4;
row[1] = "Chef Anton's Cajun Seasoning";
row[2] = 2;
row[3] = false;
row[4] = true;
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = 5;
row[1] = "Chef Anton's Gumbo Mix";
row[2] = 2;
row[3] = true;
row[4] = true;
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = 47;
row[1] = "Zaanse koeken";
row[2] = 3;
row[3] = true;
row[4] = true;
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = 48;
row[1] = "Chocolade";
row[2] = 3;
row[3] = false;
row[4] = false;
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = 49;
row[1] = "Maxilaku";
row[2] = 3;
row[3] = true;
row[4] = false;
tbl.Rows.Add(row);
return tbl;
}
#endregion
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>RepeaterCheckBoxAutoPost</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table border="1"><tr><td></td></tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:CheckBox ID="chk" runat="server" AutoPostBack="true" OnCheckedChanged="chk_CheckedChanged" /></td>
<td><%# Eval("ProductName") %></td>
<td><asp:label ID="lblProductName" runat="server" text='<%# Eval("ProductName") %>' /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:repeater>
</div>
</form>
</body>
</html>