1

我想在后面的代码中使用带有 ID 的 Label 控件TextLabel,但这给了我以下异常Object reference not set to an instance of an object.异常是在代码后面文件中的这行代码上:

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

  string text = label.Text;

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

asp代码:

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

3 回答 3

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;
    }
}
于 2013-03-10T13:38:26.073 回答
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;
    }
}
于 2013-03-10T13:46:10.583 回答
1

您必须检查正确的输入ItemTypeItemDataBound因为它是为每个项目调用的,所以是第 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;
      }
}
于 2013-03-10T13:39:39.653 回答