Search code examples
checkboxforeachrepeaterasp.net-3.5

Get values of all checkboxes in repeater


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?


Solution

  • 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
                }
            }