将控件动态绑定到 asp:DataList 中的占位符

本文关键字:DataList 占位符 asp 控件 动态绑定 | 更新日期: 2023-09-27 18:30:48

我似乎无法弄清楚这一点,但我正在尝试在运行时将用户控件添加到 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";
       }
    }
}

我错过了什么?

将控件动态绑定到 asp:DataList 中的占位符

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

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