Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
466 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...