如何在asp转发器中找到嵌套控件

时间:2012-01-18 14:28:33

标签: c# asp.net

我试图在我的转发器中找到<span id="source">,listControl将返回null。

<asp:Repeater id="rptRssFeed" runat="server" OnItemDataBound="RssFeedItemDataBound">
    <HeaderTemplate><ul></HeaderTemplate>
    <FooterTemplate></ul></FooterTemplate>
    <ItemTemplate>
        <li id="socialListItem" runat="server">
            <a href="<%# GetNavigationLink(Container.DataItem) %>" target="_blank" id="title" runat="server"><%# GetTitle(Container.DataItem) %></a>
            <span class="source" id="source" runat="server"><%# GetSource(Container.DataItem) %></span>
            <p><%# GetTeaser(Container.DataItem) %></p>
        </li>
    </ItemTemplate>
    <AlternatingItemTemplate>
        <li class="alt" id="socialListItem" runat="server">
            <a href="<%# GetNavigationLink(Container.DataItem) %>" target="_blank" id="title" runat="server"><%# GetTitle(Container.DataItem) %></a>
            <span class="source" id="source" runat="server"><%# GetSource(Container.DataItem) %></span>
            <p><%# GetTeaser(Container.DataItem) %></p>
        </li>
    </AlternatingItemTemplate>
</asp:Repeater>

public void RssFeedItemDataBound(object sender, RepeaterItemEventArgs e)
{
    HtmlGenericControl listControl = (HtmlGenericControl)e.Item.FindControl("socialListItem");
    if (!ShowSource)
    {
        HtmlGenericControl spanControl = (HtmlGenericControl)listControl.FindControl("source");
        spanControl.Visible = false;
    }
    listControl.Attributes["class"] += ((XmlFeedItem)e.Item.DataItem).XmlFeedType;
}

1 个答案:

答案 0 :(得分:3)

您需要检查是否正在检查ListItemType.Item或AlternatingItem类型中的List Item。

public void RssFeedItemDataBound(object sender, RepeaterItemEventArgs e)
    {

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {

            HtmlGenericControl listControl = (HtmlGenericControl)e.Item.FindControl("socialListItem");

            if (listControl != null)
            {
                if (!ShowSource)
                {
                    HtmlGenericControl spanControl = (HtmlGenericControl)listControl.FindControl("source");
                    spanControl.Visible = false;
                }

                listControl.Attributes["class"] += ((XmlFeedItem)e.Item.DataItem).XmlFeedType;
            }
        }
    }