I have the following repeater below and I am trying to find lblA in code behind and it fails. Below the markup are the attempts I have made:
<asp:Repeater ID="rptDetails" runat="server"> <HeaderTemplate> <table> </HeaderTemplate> <ItemTemplate> <tr> <td><strong>A:</strong></td> <td><asp:Label ID="lblA" runat="server"></asp:Label> </td> </tr> </ItemTemplate> </asp:Repeater> </table>
First I tried,
Label lblA = (Label)rptDetails.FindControl("lblA");
but lblA was null
Then I tried,
Label lblA = (Label)rptDetails.Items[0].FindControl("lblA");
but Items was 0 even though m repeater contains 1 itemtemplate
For accessing the inner repeater control you'll need to make use a RepeaterItem class that will help you to access the inner repeater control or any control that is placed inside the ItemTemplate or FooterTemplate or AlternatingItemTemplate class, by using the FindControl method of the RepeaterItem class.
The Repeater control allows you to split markup tags across the templates. To create a table using templates, include the begin table tag ( <table> ) in the HeaderTemplate, a single table row tag ( <tr> ) in the ItemTemplate, and the end table tag ( </table> ) in the FooterTemplate.
A GridView control is used when you want to display a set of data in a table format. A Repeater is when you want to display data repeatedly, but not necessarily in a tabular format. If you want a table, use a GridView, otherwise use a Repeater. The speed of loading/updating is negligible between the two.
You need to set the attribute OnItemDataBound="myFunction"
And then in your code do the following
void myFunction(object sender, RepeaterItemEventArgs e) { Label lblA = (Label)e.Item.FindControl("lblA"); }
Incidentally you can use this exact same approach for nested repeaters. IE:
<asp:Repeater ID="outerRepeater" runat="server" OnItemDataBound="outerFunction"> <ItemTemplate> <asp:Repeater ID="innerRepeater" runat="server" OnItemDataBound="innerFunction"> <ItemTemplate><asp:Label ID="myLabel" runat="server" /></ItemTemplate> </asp:Repeater> </ItemTemplate> </asp:Repeater>
And then in your code:
void outerFunction(object sender, RepeaterItemEventArgs e) { Repeater innerRepeater = (Repeater)e.Item.FindControl("innerRepeater"); innerRepeater.DataSource = ... // Some data source innerRepeater.DataBind(); } void innerFunction(object sender, RepeaterItemEventArgs e) { Label myLabel = (Label)e.Item.FindControl("myLabel"); }
All too often I see people manually binding items on an inner repeater and they don't realize how difficult they're making things for themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With