title: Automate control creation in windows forms designer
body: <p>I need to automate creation and configuration of several controls in the form  while in design mode.</p>
  
  <p>For things like that, I create a control that interacts and modifies some other controls in the form and sets default values, adds columns to grids,... Once done, I remove the control and that's it. </p>
  
  <p>This is a not quite elaborate technique to create ad-hoc macros, but it works like a charm to ease repetitive work configuring properties, specially with "big" objects with a lot of elements like grids.</p>
  
  <p>The problem is that I'm not able to create new controls and add them to the form dynamically <strong>while in design mode</strong>. Consider the following code (just a simplified example):</p>
  
  <pre><code>  public partial class ButtonCreator : UserControl
  
      [Category("Automation")]
      public int LeftPosition { get; set; }
  
      [Category("Automation")]
      public bool AutoCreate
      {
          get { return false; }
          set
          {
              var form = FindForm();
  
              if (value)
              {
                  for (var i = 10; i &lt; 100; i = i + 20)
                  {
                      var button = new Button(){Name = "btn_" + DateTime.Now.Ticks + "_" + i};
                      form.Controls.Add(button);
                      button.Location = new Point(LeftPosition, i);
                      button.BringToFront();
                  }
              }
          }
      }
  </code></pre>
  
  <p>(I've also tried using a component designer with a similar code, but with the same result, so this way is much less verbose)</p>
  
  <p>To use this I add an instance of ButtonCreator to the Form, then I set the AutoCreate property (while in design mode, from the property list). Apparently It works and adds the buttons to the form, but they are not serialized to the autogenerated C# code and I lose them after saving.</p>
  
  <p>Is there something I can do to force them to serialize when Visual studio generates the designer.cs file? </p>
  
  <p>Consider this restriction: This is not code to be released, just dirty code to ease development, therefore I prefer to avoid more complex techniques to be able to introduce changes easily, right while coding. References to Visual Studio automation, or creating visual studio extensions should be avoided if possible. </p>