Dynamically adding a user control to a repeater

天涯浪子 提交于 2019-12-05 10:17:40

I had done this a long time ago for creating nested reports using Accordions.

In Index, when you want to dynamically add User Control instances:

// Declare Placeholder    
PlaceHolder ph = (PlaceHolder)e.Item.FindControl("SubItemPlaceholder")

// Adding some literal controls to header
ph.Controls.Add(new LiteralControl("This is the accordion header!!"));

// Declare new control variable
crt = new Control();

// Load up your User Control
crt = LoadControl("~/MyControl.ascx");

// Check if it has loaded properly
if (crt != null)
{
    // GET / SET any custom properties of the User Control
    ((myClass)crt).title = "Welcome";

    // Add the new User Control to the placeholder's controls collection
    ph.Controls.Add(crt);
}

Note: In the User Control, you must add the "ClassName" in the declaration tag

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyControl.ascx.cs" Inherits="myTest" ClassName="myClass" %>

Also, any properties you wish to expose when creating instances dynamically, you declare them as follows:

public string title { get; set; }

So if you want to force a value when creating for "repMyClass" you can set it as a property and assign whatever value you want to it programmaticaly.

You can make another constructor in the control that takes the property you want and use it in the load event, and then pass it in the currently empty object array in LoadControl() call.

Another approach is to fire the logic in the setter of the property instead of in the Load event of the control, since is essentially the real load here and fires once per request per control if I get it right.

Another approach is not to load it dynamically as all.

inside your item template you can have something like:

<uc:MyControl runat="server 
    ChildItems='<%# ((MyClass) Container.DataItem).Children %>'
    Visible='<%# ((MyClass) Container.DataItem).Children.Length > 0 %>'
    />

Update

One more approach that never gave me errors with child controls in user controls inside repeaters or page life cycle, is to use the Item Data Bound event instead of the Item Created.

Actually, when I think about it now, your code shouldn't because e.Item.DataItem hasn;t been bound to yet.

Try to change the event to ItemDataBound and see if this works.

.

I still though recommend you include the control in the item markup, and control the visibility of the control in the event (now to be ItemDataBound). You can refer to the control by something like e.Item.FindControl("ControlId") as MyControl (will return null if not found in current item).

Try combining both, or at least changing event to data bound instead of created, and let's see...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!