views:

264

answers:

2

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.

A: 

why don't you try adding it in Page_LoadComplete

myc.Controls.Add(NewParent);
TheVillageIdiot
I think you're talking about doing this from the Page itself, or the parent of both controls. Doing it from the page works. I can place the code you wrote in the page's OnInit and it will work fine. The problem is when a control tries to move around a sibling. The parent (in this case the page itself) seems to be able to do this, but doesn't work across the same tree level.I could do what you suggest, but it would be more maintenance work for me; I rather the control itself take care of that and plus I need to tweak where exactly in MyControl it should be added / rendered. Thanks.
pbz
A: 

I couldn't reproduce it, but as aman.tur suggested, have you tried another event? Overriding CreateChildControls() seems like the right place for it.

Kobi
I posted a sample of what MyControl looks like. Moving the code from OnInit to CreateChildControls still gives me that error. To clarify, I'm trying to change the parent of an outside control to be part of MyControl, not create a new child control that would belong to MyControl. So, something else creates the control, I just want to move it around.
pbz