Cannot Find Label Control In Repeater Control

冷暖自知 提交于 2019-12-11 08:57:51

问题


I want to take the Label control with ID TextLabel in the code behind, but this give me the following exception Object reference not set to an instance of an object. The exception is on this line of code in code behind file:

  Label label = e.Item.FindControl("TextLabel") as Label;

  string text = label.Text;

What mistake I made here ? How to find "TextLabel" control in code behind ?

aspx code:

<asp:Repeater ID="UserPostRepeater" runat="server" OnItemDataBound="UserPostRepeater_ItemDataBound">
    <HeaderTemplate>
    </HeaderTemplate>
    <ItemTemplate>

        <asp:Label ID="TextLabel" runat="server" Text="Label"></asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    </FooterTemplate>
</asp:Repeater>

code-behind:

protected void UserPostRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    BlogProfileEntities blogProfile = new BlogProfileEntities();
    Label label = e.Item.FindControl("TextLabel") as Label;
    string text = label.Text;
}

回答1:


When using the ItemDataBound you need to check the type of repeater item - e.Item.ItemType.

It needs to be either ListItemType.Item or ListItemType.AlternatingItem - these are the templates where the label exists.

protected void UserPostRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    BlogProfileEntities blogProfile = new BlogProfileEntities();

    if (e.Item.ItemType == ListItemType.Item || 
        e.Item.ItemType == ListItemType.AlternatingItem)
    {
      Label label = e.Item.FindControl("TextLabel") as Label;
      string text = label.Text;
    }
}



回答2:


You have to check for the correct ItemType in ItemDataBound since it is called for every item, so for the Header first.

protected void UserPostRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
     // This event is raised for the header, the footer, separators, and items.
      // Execute the following logic for Items and Alternating Items
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) 
      {
         Label label = e.Item.FindControl("TextLabel") as Label;
         string text = label.Text;
      }
}



回答3:


You need to specify what type of ItemType it is. This will work in your case:

protected void UserPostRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)  // Add this
    {
     Label label = e.Item.FindControl("TextLabel") as Label;
     string text = label.Text;
    }
}


来源:https://stackoverflow.com/questions/15322781/cannot-find-label-control-in-repeater-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!