2 November 2007
ASP.NET: Checkboxes in the Repeater Control
Posted by Mikhail Esteves under: C#; Tips .
Placing checkboxes in a .NET Repeater control is pretty straight-forward:
< asp:repeater id="rpResults" runat="server">
< li>< asp:checkbox id="chkbx" runat="server />
< %#Eval("project_name")%>< /li>
< /asp:repeater>
Now if you want to add values to each of those checkboxes, and retrieve them (on form submit, for example), you would need to use the Repeater control’s OnItemDataBound method to attach an attribute to each checkbox. Here is how you would do that using C#, assuming you want to attach project_id to each checkbox:
protected void rpResults_ItemDataBound(...)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
((CheckBox)e.Item.FindControl("chkbx")).Attributes
.Add("project_id",
((DataRowView)e.Item.DataItem)["project_id"].ToString());
}
}
Now to get those items back on form submit, you would do:
foreach (RepeaterItem rpItem in rpResults.Items)
{
CheckBox chkbx = rpItem.FindControl("chkbx") as CheckBox;
if (chkbx.Checked)
{
Response.Write("Checked Project: " +
chkbx.Attributes["project_id"].ToString() + "< br />");
}
}
That’s it!
2 Comments so far...
Mariana Says:
5 November 2007 at 4:32 am.
thanks so much
Chris Says:
30 January 2008 at 1:59 am.
Awesome, thanks much.