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!

Options


6 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.

cosmoMarch 30th, 2011 at 4:06 am

My god, I’ve seen so many contrived examples and so many, just plain, bad answers to this question.

You’ve made it so easy.
Thanks!

Paul SmithJuly 29th, 2011 at 9:36 pm

awesome thanks for this… very quick and precise solution

JiyaOctober 14th, 2011 at 5:11 pm

I have a nested repeater, which displays categories(parent repeater) and
corresponding subcategories(child repeater). Both repeaters have checkboxes.
When I check category checkbox and subcategory check boxes and click on
submit button , I have to retrieve the corresponding categoryid and
subcategory id, so that I can store it to a table. I am getting the
categoryid but I am failing to get subcategoryid(actually I don’t know how to
retrieve it).

Leave a comment

Your comment