24
votes

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

5

5 Answers

30
votes

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.

8
votes

I just had the same problem.

We are missing the item type while looping in the items. The very first item in the repeater is the header, and header does not have the asp elements we are looking for.

Try this:

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {Label lblA = (Label)rptDetails.Items[0].FindControl("lblA");}
2
votes

Code for VB.net

    Protected Sub rptDetails_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptDetails.ItemDataBound    
      If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
        Dim lblA As Label = CType(e.Item.FindControl("lblA"), Label)
        lblA.Text = "Found it!"
      End If
    End Sub
0
votes

You should bind first.
for example)

rptDetails.DataSource = dataSet.Tables["Order"];

rptDetails.DataBind();