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