title: How do I create buttons dynamically in C# onClick of another button? And then have those buttons also do the same
body: <p>I am trying to make a C# web page that creates buttons dynamically based on what the form submits, but I keep running to dead ends.  The problem is that (apparently?) you can only hook up EventHandlers during the Page_Load, and not inside a button's Click event?  </p>
  
  <p>Basically I have some code to create a button:</p>
  
  <pre><code>private Button CreateButton(string id, string text) {
      Button b = new Button();
      b.ID = id;
      b.Text = text;
      b.Command += new CommandEventHandler(Button_Command);
      b.CommandArgument = text;
      return b;
  }
  </code></pre>
  
  <p>And when these new buttons are clicked, they are supposed to pass command arguments, and create new buttons based on those command arguments</p>
  
  <pre><code>void Button_Command(object sender, CommandEventArgs e) {
      //Put code here that creates new buttons based on what's submitted
      DoThis(e.CommandArgument.ToString());
  }
  </code></pre>
  
  <p>But when I run this code inside a button's Click Event, the EventHandler for the newly created buttons don't get hooked up.  </p>
  
  <p>There is only a text input and a GO button the first time you hit the page.  It should create a bunch of new buttons along with their command arguments:</p>
  
  <pre><code>protected void bntGo_Click(object sender, e EventArgs){
      DoThis(txtInput.Text);
  }
  
  private void DoThis(string arg){
      //Do some logic to create a Dictionary&lt;string, int&gt; object (sortedDict) 
      //based on the arg passed, then for each KeyValuePair in the Dictionary, 
      //add a button to a panel on the page, setting each button's commandarguments 
      //to each string in the dictionary
      int count=1;
      foreach (KeyValuePair&lt;string, int&gt; pair in sortedDict) {
          pnlButtonsPanel.Controls.Add(CreateButton("Btn"+count.ToString(), pair.Key));
      }
  }
  </code></pre>
  
  <p>How do I accomplish this?  I can't just run the DoThis() function every time the page loads because DoThis() needs to be passed CommandArguments from the button that they clicked, which is not available inside page_load.</p>
  
  <p>What am I doing wrong?  I need a new approach.  I'm thinking myself in circles here.</p>
  
  <p>Thanks!</p>