该例子实现在Repeater通过勾选CheckBox后,通过底部按钮获取到所选的所有数据(之后可以进行批量删除、更新等操作)
首先,定义一个类
public class UserInfo
{
public int ID { get; set; }
public string name { get; set; }
}
在页面上编写Repeater模板
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table style="width: 100%;">
<tr>
<td>
ID
</td>
<td>
名称
</td>
<td>
操作
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#Eval("ID")%>
</td>
<td>
<%#Eval("name")%>
</td>
<td>
<asp:CheckBox ID="CheckBox1" runat="server" dataID='<%#Eval("ID")%>' />操作
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
数据初始化
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<UserInfo> userList = new List<UserInfo>();
for (int i = 0; i < 10; i++)
{
UserInfo user = new UserInfo();
user.ID = i;
user.name = "BDS";
userList.Add(user);
}
Repeater1.DataSource = userList;
Repeater1.DataBind();
}
}
页面添加一个遍历操作的按钮
asp:Button ID="Button1" runat="server" Text="遍历Repeater" οnclick="Button1_Click" />
遍历操作代码
protected void Button1_Click(object sender, EventArgs e)
{
List<int> idList = new List<int>();
foreach (RepeaterItem item in Repeater1.Items)
{
CheckBox cb = item.FindControl("CheckBox1") as CheckBox;
if (cb.Checked)
{
int id = int.Parse(cb.Attributes["dataID"]);
idList.Add(id);
}
}
foreach (var item in idList)
{
Response.Write(item + ",");
}
}