在中继器控制中找不到标签控制

时间:2013-03-10 13:31:07

标签: c# asp.net exception repeater

我想在后面的代码中使用标识为TextLabel的Label控件,但这会给我以下异常Object reference not set to an instance of an object.例外的代码隐藏在文件后面的代码行中:

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

  string text = label.Text;

我在这里弄错了什么?如何在代码后面找到“TextLabel”控件?

aspx代码:

<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>

代码隐藏:

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

3 个答案:

答案 0 :(得分:5)

使用ItemDataBound时,您需要检查转发器项目的类型 - e.Item.ItemType

它必须是ListItemType.ItemListItemType.AlternatingItem - 这些是标签所在的模板。

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;
    }
}

答案 1 :(得分:1)

您必须在ItemType中检查正确的ItemDataBound,因为它是针对每个项目进行调用的,因此首先是Header

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;
      }
}

答案 2 :(得分:1)

  

您需要指定它的ItemType类型。这适用于您的情况:

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;
    }
}