ASP.NET dynamically reassign controls in the control tree
Posted
by pbz
on Stack Overflow
See other posts from Stack Overflow
or by pbz
Published on 2009-06-02T04:16:13Z
Indexed on
2010/04/11
11:03 UTC
Read the original article
Hit count: 408
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.
© Stack Overflow or respective owner