ASP.NET: Checkboxes in the Repeater Control

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!

  • Share/Bookmark

3 Comments

MarianaNovember 5th, 2007 at 4:32 am

thanks so much

ChrisJanuary 30th, 2008 at 1:59 am

Awesome, thanks much.

Alexander JonasMay 13th, 2009 at 2:53 am

Thanks, this was exactly what I needed.

Leave a comment

Your comment