Get values of all checkboxes in repeater

dmr picture dmr · May 22, 2013 · Viewed 20.8k times · Source

When the user clicks a "Save Changes" button, I need to get the values of all the checkboxes inside a repeater. If I can't get the values, the ID is also ok.

Master page code:

<ul class="bulletless">
    <asp:Repeater runat="server" ID="newsletter_repeater">
        <ItemTemplate>
            <li><input type="checkbox" value='<%#Eval("id")%>' id='<%#Eval("id")%>'/> <%#Eval("displayTitle")%></li>
        </ItemTemplate>
     </asp:Repeater>
</ul>

<asp:Button runat="server" CssClass="editButtonOff" Text="Save Changes" ID="SaveNewsletterChanges" OnClick="SaveNewsletterChanges_submit" />

Here is my code behind:

protected void SaveNewsletterChanges_submit(object sender, EventArgs e)
{
    //the count of the items in the repeater is 2
    //but the aItem is null
        foreach( RepeaterItem aItem in newsletter_repeater.Items){
        string myId = aItem.ID;
    }
}

What am I doing wrong?

Answer

Shai Cohen picture Shai Cohen · May 23, 2013

First, you need to add runat="server" to your checkbox.

Second, you need to assign the checkbox an id that does not change. The repeater will take care of making the client-side id unique: id="chkDisplayTitle"

Third, you access items in the repeater like so:

foreach (RepeaterItem item in CourseAreaRptr.Items)
        {
            HtmlInputCheckBox chkDisplayTitle = (HtmlInputCheckBox)item.FindControl("chkDisplayTitle");
            if (chkDisplayTitle.Checked)
            {
                //HERE IS YOUR VALUE: chkAddressSelected.Value
            }
        }