title: Nested Panels: 'child' is not a child control of this parent
body: <p>I've got a class that inherits from Panel. It contains a second panel nested inside of it. When controls are added to this control, I actually want them added to the <em>inner</em> panel. The goal here is to draw a special border using the outer panel, but then be able to host controls inside of the inner panel as if it were any other panel.</p>
  
  <p>Here is the basic code I'm using:</p>
  
  <pre><code>public class TestPanel2 : Panel
  {
      private Panel innerPanel = new Panel();
  
      public TestPanel2()
      {
          this.Controls.Add(innerPanel);
          this.ControlAdded += new ControlEventHandler(TestPanel2_ControlAdded);
      }
  
      void TestPanel2_ControlAdded(object sender, ControlEventArgs e)
      {
          if (e.Control != innerPanel) {
              innerPanel.Controls.Add(e.Control);
          }
      }
  }
  </code></pre>
  
  <p>When using this control in the Designer, dragging a child control (such as a CheckBox) into it results in the designer reporting:</p>
  
  <pre><code>'child' is not a child control of this parent
  </code></pre>
  
  <p>My theory is that the Designer is calling Controls.SetChildIndex() or Controls.GetChildIndex() for its own purposes, and that is triggering the error. So I tried adding the following property to the class:</p>
  
  <pre><code>    public new ControlCollection Controls
      {
          get { return innerPanel.Controls; }
      }
  </code></pre>
  
  <p>When I did this, I also changed all internal references of this.Controls to base.Controls. However, this didn't resolve the problem.</p>
  
  <p>Is there a way to add a nested panel that automatically receives controls that are dragged into it? If I change the code so that the child controls are only added to innerControl at runtime, it works, but the position of the child controls ends up being wrong, so it isn't much of a solution.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>For whatever it is worth, here is a simplified diagram of what I am trying to do. I'm creating a toolkit that will be used by other developers. It is a specialized panel that contains a custom border and title block. Think of it as being functionally similar to a "GroupBox" control. I want them to be able to drag this specialized panel onto their form, and then add controls to it, all within the Designer. The "innerPanel" needs to be its own panel so that it is the only region scrolled (when scrolling is necessary).</p>
  
  <p><a href="https://i.stack.imgur.com/GasoF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GasoF.png" alt="title block panel diagram"></a><br>
  <sub>(source: <a href="http://cosmicjive.net/tempimages/NestedPanel.png" rel="nofollow noreferrer">cosmicjive.net</a>)</sub>  </p>