Can't find control within asp.net repeater?

前端 未结 5 1090
广开言路
广开言路 2020-12-08 20:19

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:



        
相关标签:
5条回答
  • 2020-12-08 20:56

    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");}
    
    0 讨论(0)
  • 2020-12-08 20:57

    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 讨论(0)
  • 2020-12-08 20:57

    You should bind first.
    for example)

    rptDetails.DataSource = dataSet.Tables["Order"];
    
    rptDetails.DataBind();
    
    0 讨论(0)
  • 2020-12-08 20:59

    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.

    0 讨论(0)
  • 2020-12-08 21:09

    Investigate the Repeater.ItemDataBound Event.

    0 讨论(0)
提交回复
热议问题