Imagine you have a list of some items and checkboxes next to each item providing the ability for a user to make multiple choices and submit a result in one go. Weather you are implementing a news groups subscription, user survey or online products catalogue - the code behind is the same: we bind some object list to a data control like Repeater, add a checkbox to every item, set checkbox value to item ID.
Here is an example with list of books available for order
<asp:Repeater ID="rptBooks" runat="server">
<td><input type="checkbox" runat="server" value='<%# Eval("BookID")%>' ID="chkBox" /></td>
<td><%# Eval("Author")%> </td>
<asp:Button ID="btnOrder" OnClick="btnOrder_Click" runat="server" Text="Order" />
When “Order” button is clicked we need get all selected book IDs (we store them in a value field of each checkbox). I suggest that we create an extension method that will do all the work and when we need to get selected items in any repeater in our code we will have to call only one method GetSelectedItems
public static class RepeaterExt
/// Returns selected items array list in a repeater rpt
/// <param name="chkBoxId">ID of a checkbox used in repeater to store the value of each item</param>
public static ArrayList GetSelectedItems(this Repeater rpt, string chkBoxId)
var selectedValues = new ArrayList();
for (int i = 0; i < rpt.Items.Count; i++)
var chkBox = rpt.Items[i].FindControl(chkBoxId) as HtmlInputCheckBox;
if (chkBox != null && chkBox.Checked)
Now if we go back to our page with books catalog we can right the following:
protected void btnOrder_Click(object sender, EventArgs e)
selectedValues array will contain BookIDs that were ordered and you can store them in the database or process as required by your code.
Note that this example assumes that you need to use <input runat=”server”… to be able to pre-polulate checked values or keep the state of the checkboxes after the postback. If none of this functionality is needed, the simplest way to get selected values is to use standard html
<input type="checkbox" value='<%# Eval("BookID")%>' name="chkBox" />
When the “Order” button is clicked Request["chkBox"] will return comma delimited list of selected BookIDs.