title: Dynamic creation of Button OK but its event handler NOT executed?
body: <p>I have following simple controls on a page</p>
  
  <p><code>WebForm1.aspx</code>      </p>
  
  <pre><code>&lt;asp:Panel ID="Panel1" runat="server"&gt;
  &lt;/asp:Panel&gt;
  &lt;br /&gt;
  &lt;asp:Label ID="lblContent" runat="server" &gt;&lt;/asp:Label&gt;
  </code></pre>
  
  <p>Some code behind in <code>WebForm1.aspx.cs</code> :</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
      Button btn = new Button();
      btn.ID = "btnTest";
      btn.Text = "I was dynamically created";
      btn.Click += new EventHandler(btnTest_Click);
      Panel1.Controls.Add(btn);
  }
  
  void btnTest_Click(object sender, EventArgs e)
  {
      lblContent.Text = "btnTest_Click: " + DateTime.Now.ToString();
  }
  </code></pre>
  
  <p>In short, when I dynamically create a Button (<code>btnTest</code>) in the <code>Page_Load</code> event and assign event handler <code>btnTest_Click</code> to the button. Click event then, when loading the page I see <code>btnTest</code> appearing and when clicking on it the event handler <code>btnTest_Click</code> is invoked. OK,  No problem.</p>
  
  <p>I have a problem though when I try following scenario... first, I add a button to the page in designer mode.</p>
  
  <pre><code>&lt;asp:Panel ID="Panel1" runat="server"&gt;
  &lt;/asp:Panel&gt;
  &lt;asp:Button     ID="btnCreateDynamically" runat="server" 
              Text="Create Button Dynamically" 
                  onclick="btnCreateDynamically_Click" /&gt;
  &lt;br /&gt;
  &lt;asp:Label ID="lblContent" runat="server" &gt;&lt;/asp:Label&gt;
  </code></pre>
  
  <p>I move the code from <code>Page_Load</code> to the button event handler of <code>btnCreateDynamically</code> as follows</p>
  
  <pre><code>protected void btnCreateDynamically_Click(object sender, EventArgs e)
  {
      Button btn = new Button();
      btn.ID = "btnTest";
      btn.Text = "I was dynamically created";
      btn.Click += new EventHandler(btnTest_Click);
      Panel1.Controls.Add(btn);
  }
  </code></pre>
  
  <p>When running the WebApp now and clicking on <code>btnCreateDynamically</code>, btnTest is created but when I click on <code>btnTest</code>  its event handler is NOT invoked ???</p>
  
  <p>Why not?
  How can I make this work?</p>