ASP.NET dynamically reassign controls in the control tree
- by pbz
Let's say I have a custom control that looks like this
<cc:MyControl runat="server" ID="myc" LinkControlID="NewParent" />
and, on the same page:
<asp:TextBox runat="server" ID="NewParent" />
What I would like to do is, from MyControl, change NewParent's parent so that it would be part of MyControl's Controls collection. When I try to do this, from OnInit, I get:
The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.
Which makes sense, but is there a way around this? I'm OK if NewParent remains the child of the Page as long as from MyControl I can somehow redirect the rendering to MyControl's control.
Can this be done? Thanks.
EDIT:
To clarify here's a mockup of MyControl:
public class MyControl : Panel
{
protected override void OnInit(System.EventArgs e)
{
base.OnInit(e);
if (!String.IsNullOrEmpty(LinkControlID))
{
Control link = Parent.FindControl(LinkControlID);
if (link != null)
{
Controls.Add(link);
}
}
}
public string LinkControlID { get; set; }
}
This assumes that MyControl and LinkControlID are placed on the same level in the tree hierarchy, which is OK in my case.