2

我想知道如何有条件地将用户控件添加到中继器控件。我试图将它添加到中继器控件中但无法加载用户控件的占位符。以下代码不起作用。

<asp:Repeater ID="ResultsRepeater" runat="server">
        <HeaderTemplate></HeaderTemplate>
        <ItemTemplate>  
        <div>
            <asp:PlaceHolder ID="PlaceHolder1" runat="server">
            </asp:PlaceHolder>
        </div>
        </ItemTemplate>
</asp:Repeater>

 public void GetStatus(int i)
    {
        UserControl uc = new UserControl();
        if(i==1)
        {
            uc = LoadControl("DraftList.ascx") as UserControl;
        }
        else if(i==2)
        {
             uc = LoadControl("FinalList.ascx") as UserControl;
        }


        PlaceHolder p1 = (PlaceHolder)ResultsRepeater.Items[0].FindControl("PlaceHolder1");
        p1.Controls.Add(uc);

    }
4

2 回答 2

4

是否有某种原因您不想只在 aspx 中处理所有这些?那将是最简单和最干净的选择:

<asp:Repeater runat="server" ID="ResultsRepeater">
    <ItemTemplate>
        <uc1:DraftList ID="DraftList1" runat="server" Visible='<%# ((int)Eval("Status") == 1)%>' />
        <uc2:FinalList ID="FinalList1" runat="server" Visible='<%# ((int)Eval("Status") == 2)%>' />
    </ItemTemplate>
</asp:Repeater>

如果控件不可见(即Visible=false),则不会呈现任何标记,因此以这种方式编码不会为服务器或客户端浏览器创建更多工作,同时具有更易于阅读和提供用户控制的好处设计时的属性。

您只需要确保在页面顶部注册您的控件:

<%@ Register src="DraftList.ascx" tagname="DraftList" tagprefix="uc1" %>
<%@ Register src="FinalList.ascx" tagname="FinalList" tagprefix="uc2" %>
于 2012-05-22T14:13:08.503 回答
2

为什么不尝试在中继器 ItemDataBound 事件中添加它?IE,

<asp:Repeater ID="ResultsRepeater" OnItemDataBound="ResultsRepeater_ItemDataBound" runat="server">
        <HeaderTemplate></HeaderTemplate>
        <ItemTemplate>  
        <div>
            <asp:PlaceHolder ID="PlaceHolder1" runat="server">
            </asp:PlaceHolder>
        </div>
        </ItemTemplate>
</asp:Repeater>

在后面的代码中

protected void ResultsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Panel PlaceHolder1 = (Panel)e.Item.FindControl("PlaceHolder1");

            // declare/obtain the value of i given the DataItem
            // e.g.,
            int i = ((int)e.Item.DataItem); // or however you're getting i

            if (i == 1)
            {
                var uc = LoadControl("~/DraftList.ascx");
                PlaceHolder1.Controls.Add(uc);
            }
            else if (i == 2)
            {
                var uc = LoadControl("~/FinalList.ascx");
                PlaceHolder1.Controls.Add(uc);
            }
        }
    }

从您最后的评论(对问题)来看,您可能还需要确保您已将数据源附加并绑定到转发器。IE,

ResultsRepeater.DataSource = dataSource; //whatever your datasource is e.g., datatable, IEnumerable list etc
ResultsRepeater.DataBind();
于 2012-05-22T10:23:10.650 回答