C# - Looping through a Repeater control and accessing values added via DataBinder.Eval()

PercivalMcGullicuddy picture PercivalMcGullicuddy · Aug 31, 2011 · Viewed 22.8k times · Source

I have a Repeater control that adds rows to a table. The data inside each cell comes from a Datatable that is bound to the repeater.

Simplified Example:

<asp:Repeater ID="Repeater1" runat="server">
  <ItemTemplate>
   <tr>
     <td>
        <%# DataBinder.Eval(Container.DataItem, "PartNumber")%>
     </td>
     <td>
         <%# DataBinder.Eval(Container.DataItem, "Quantity")%>
     </td>
   </tr>
</ItemTemplate>

In code behind I would like to be able to loop through each repeater row and get the value for Quantity for that row.

So far all I have is:

foreach (RepeaterItem ri in Repeater1.Items)
{

} 

Answer

James Johnson picture James Johnson · Aug 31, 2011

I would put the content in Labels, and access the Labels in the code behind:

<asp:Repeater ID="Repeater1" runat="server"> 
   <ItemTemplate> 
   <tr> 
     <td> 
         <asp:Label ID="lblPartNumber" runat="server" Text='<%#Eval("PartNumber")%>' /> 
     </td> 
     <td> 
         <asp:Label ID="lblQuantity" runat="server" Text='<%#Eval("Quantity")%>' />
     </td> 
   </tr> 
   </ItemTemplate> 
</asp:Repeater>

And in the code behind:

foreach (RepeaterItem ri in Repeater1.Items)
{
    Label quantityLabel = (Label)ri.FindControl("lblQuantity");
    Label partNumberLabel = (Label)ri.FindControl("lblPartNumber");

    string quantityText = quantityLabel.Text;
    string partNumberText = partNumberLabel.Text;
}