C# - Looping through a Repeater control and accessing values added via DataBinder.Eval()
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)
{
}
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;
}
You could use labels:
<td>
<asp:Label ID="lblPartNumber" runat="server" Text='<%#Eval("PartNumber")%>' />
</td>
<td>
<asp:Label ID="lblQuantity" runat="server" Text='<%#Eval("Quantity")%>' />
</td>
And grab the values of the labels on the repeater OnItemDataBound event.
protected void repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
foreach (Control c in e.Item.Controls)
{
if (c is Label)
{
// Grab label
Label lbl = c as Label;
String your_value = lbl.Text;
}
}
}
You'd want to set DataKeys on the repeater so that you can retrieve them later.
http://www.singingeels.com/Articles/The_ListView_Dominates_The_Repeater.aspx
EDIT: By the way, I just googled "Repeater DataKeys" and found this article at the top... I wrote the article 4 years ago, so please don't be cruel! (there is sample C# code in there you can look at).
it's possible to do what you ask by retrieving the items inside the ri
element, meaning that you "could" access its content.
Usually the approach, a bit better than your initial one, would be to have some controls with id and other properties inside the ItemTemplate of the repeater so you can simply do something like ri.FindControl("yourControlId")
, cast this to Label or Literal or whatever other control you have put in there and use its value or text property.
this is the usual way, better to work with IDs instead of anonymous td or tr :)
精彩评论