【问题标题】:Binding controls dynamically to PlaceHolder in asp:DataList在 asp:DataList 中将控件动态绑定到 PlaceHolder
【发布时间】:2013-09-14 19:33:39
【问题描述】:

我似乎无法弄清楚这一点,但我正在尝试在运行时将用户控件添加到 DataList(因为实际控件类型可能不同)。因此,如果我像这样在标记中对控件引用进行硬编码,它就可以工作:

<asp:DataList ID="myDL" runat="server" RepeatDirection="Horizontal" RepeatColumns="3" OnItemDataBound="myDL_Item_Bound">
    <ItemTemplate>
        <prefix:MyControl ID="myControl1" runat="server" />
    </ItemTemplate>
</asp:DataList>

但如果我尝试以编程方式将其添加到占位符,它不会呈现用户控件(只是空的 td 标签):

<asp:DataList ID="myDL" runat="server" RepeatDirection="Horizontal" RepeatColumns="3" OnItemDataBound="myDL_Item_Bound">
     <ItemTemplate>
        <asp:PlaceHolder ID="ph" runat="server">
        </asp:PlaceHolder>
    </ItemTemplate>
</asp:DataList>


protected void myDL_Item_Bound(Object sender, DataListItemEventArgs e) {
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
       PlaceHolder ph = (PlaceHolder)e.Item.FindControl("ph");
       if (ph != null) {
           MyControl ctrl = new MyControl();
           ctrl.SomeProp = "xyz";
           ph.Controls.Add(ctrl);
       }
       else {
           MyControl ctrl = (MyControl)e.Item.FindControl("myControl1");
           ctrl.SomeProp = "xyz";
       }
    }
}

我错过了什么?

【问题讨论】:

    标签: c# asp.net user-controls placeholder datalist


    【解决方案1】:

    您没有将控件添加到页面。你需要添加它:

            Control ctrl = (Control)Page.LoadControl("MyControl.ascx"); 
            // MyControl ctrl = new MyControl();
            ctrl.SomeProp = "xyz";
            ph.Controls.Add(ctrl);
    

    【讨论】:

    • @afzaluhl 谢谢!我知道的比这更清楚,我只需要第二双眼睛看着它并告诉我我在哪里搞砸了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多