Question

I can't seem to figure this one out but I'm trying to add a user control to a DataList at runtime (because the actual control type can differ). So if I hard code the control reference in the markup like this it works:

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

But if I try to add it programmatically to a placeholder, it does not render the user controls (just empty td tags):

<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";
       }
    }
}

what am I missing?

Was it helpful?

Solution

You are not adding the control to the page. You need to add it:

        Control ctrl = (Control)Page.LoadControl("MyControl.ascx"); 
        // MyControl ctrl = new MyControl();
        ctrl.SomeProp = "xyz";
        ph.Controls.Add(ctrl);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top