1

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;
}
Shai Cohen
  • 6,074
  • 4
  • 31
  • 54
TheChampp
  • 1,337
  • 5
  • 24
  • 41
  • Check your html output. You'll probably see that it gives it an ID like TextLabel_1, being the reason you cannot find it using that ID. – Mike C. Mar 10 '13 at 13:37

3 Answers3

5

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;
    }
}
Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

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;
      }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

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;
    }
}
Praveen Nambiar
  • 4,852
  • 1
  • 22
  • 31