title: Dynamically adding a commandbutton in ASP.NET
body: <p>I have a page with a dynamically created command button.</p>
  
  <p>I need to dynamically wire up a click event so I can grab the CommandArgument of the clicked button.</p>
  
  <pre><code>Button b = new Button();
  b.ID = "btnTrigger2";
  b.CssClass = "hiddenBtn";
  b.CommandName = "lbl3";
  b.Click += new EventHandler(btnTrigger_Click);
  </code></pre>
  
  <p>The problem is the last line - I can't wire up an EventHandler this way - I need to use the standard EventArgs instead of CommandEventArgs.</p>
  
  <p>Anyone have any suggestions on getting this to work? There's got to be a way...</p>
  
  <p>EDIT</p>
  
  <p>Figured I'd post the code that finally worked in case anyone else tries to do the same thing.</p>
  
  <p>`string tabLoadedScript = string.Empty;
      string postBackScript = string.Empty;</p>
  
  <pre><code>string script = " &lt;script language='javascript' type='text/javascript'&gt;" + System.Environment.NewLine;
  script += "function clientActiveTabChanged(sender, args) {" + System.Environment.NewLine;
  
  
  int i = 0;
  
  foreach(TabPanel tp in tc1.Tabs)
      {
      Button b = new Button();
      b.ID = "btn" + tp.ClientID;
      b.CssClass = "hiddenBtn";
      b.CommandName = tp.ID;
      b.Command += btnTrigger_Click;
      this.form1.Controls.Add(b);
      AsyncPostBackTrigger trg = new AsyncPostBackTrigger();
      trg.ControlID = "btn" + tp.ClientID;
  
      tabLoadedScript += "var isTab" + tp.ClientID + "loaded=$get('" + tp.Controls[0].ClientID + "');" + System.Environment.NewLine;
      postBackScript += "if(!isTab" + tp.ClientID + "loaded &amp;&amp; sender.get_activeTabIndex() == " + i + ") {" + System.Environment.NewLine;
      postBackScript += "__doPostBack('" + b.ClientID + "','');}" + System.Environment.NewLine;
      i++;
      }
  script += tabLoadedScript;
  script += postBackScript;
  script += "}" + System.Environment.NewLine;
  script += "&lt;/script&gt;";
  </code></pre>
  
  <p>this.ClientScript.RegisterClientScriptBlock(this.GetType(), "cs", script, false);</p>
  
  <p>protected void btnTrigger_Click(object sender, CommandEventArgs e)
          {
          System.Threading.Thread.Sleep(2500);
          Panel ctrl = (Panel) FindControlRecursive(this, "pnl" + e.CommandName);
          ctrl.Visible = true;
          }</p>
  
  <pre><code>public static Control FindControlRecursive(Control Root, string Id)
      {
  
      if(Root.ID == Id)
          return Root;
  
      foreach(Control Ctl in Root.Controls)
          {
  
          Control FoundCtl = FindControlRecursive(Ctl, Id);
          if(FoundCtl != null)
          return FoundCtl;
  
          }
      return null;
  
      }
  </code></pre>
  
  <p>`</p>