Vivian River
Vivian River

Reputation: 32390

How to have an ASP checkbox for each entry in a list?

I want to do something like this in my asp code:

<%
 foreach Record record in listOfRecords
{
 %>
<asp:checkbox runat="server" id="employeeIdNumber" />
<p>Employee's Name: <%= record.name %> </p>
<p>Employee's Phone Number: <%= record.phoneNumber %></p>
<%
}
%>

The problem is that the checkbox id is a string literal. How can I give a unique id to each employee's checkbox?

Upvotes: 0

Views: 396

Answers (3)

James Smith
James Smith

Reputation: 69

CheckboxList is an option too.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkboxlist.aspx

This also has an example on how to check the checked state - just iterate through and check the Selected property.

Upvotes: 0

light
light

Reputation: 816

Wrap this in a repeater. Then bind your listOfRecords to the repeater.

<asp:Repeater runat="server">
  <ItemTemplate>
    <asp:checkbox runat="server" id="employeeIdNumber" />
    <p>Employee's Name: <%# Eval("name") %> </p>
    <p>Employee's Phone Number: <%# Eval("phoneNumber") %></p>
  </ItemTemplate>
</asp:Repeater>

Then to get it out, you run through the RepeaterItems collection and look for the checkboxes by RepeaterItem.FindControl("employeeIdNumber") to determine if they are checked.

Upvotes: 1

Arief
Arief

Reputation: 6085

I think you should use Repeater instead.

<asp:Repeater ID="rptEmployees" runat="server">
    <ItemTemplate>
        <asp:CheckBox ID="employeeIDNumber" runat="server" />
    </ItemTemplate>
</asp:Repeater>

This Control will render unique ID for each checkbox for you.

Upvotes: 1

Related Questions