将控件动态绑定到asp:DataList中的PlaceHolder

时间:2013-09-10 22:46:44

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

我似乎无法解决这个问题,但我试图在运行时将用户控件添加到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";
       }
    }
}

我错过了什么?

1 个答案:

答案 0 :(得分:1)

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

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