title: Best practice for dynamically added Web.UI.ITemplate classes
body: <p>We have a couple of ASP.Net dataview column templates that are dynamically added to the dataview depending on columns selected by users.</p>
  
  <p>These templated cells need to handle custom databindings:</p>
  
  <pre><code>public class CustomColumnTemplate: 
      ITemplate
  {
      public void InstantiateIn( Control container )
      {
          //create a new label
          Label contentLabel = new Label();
  
          //add a custom data binding
          contentLabel.DataBinding +=
              ( sender, e ) =&gt;
              {
                  //do custom stuff at databind time
                  contentLabel.Text = //bound content
              };
  
          //add the label to the cell
          container.Controls.Add( contentLabel );
      }
  }
  
  ...
  
  myGridView.Columns.Add( new TemplateField
      {
         ItemTemplate = new CustomColumnTemplate(),
         HeaderText = "Custom column"
      } );
  </code></pre>
  
  <p>Firstly this seems rather messy, but there is also a resource issue. The <code>Label</code> is generated, and can't be disposed in the <code>InstantiateIn</code> because then it wouldn't be there to databind.</p>
  
  <p>Is there a better pattern for these controls? </p>
  
  <p>Is there a way to make sure that the label is disposed after the databind and render?</p>