2

I am adding x number of buttons to an asp.net web application. This is my code for doing so:

int i = 0;
foreach(var foo in bar){
    Button b = new Button();
    b.ID = "button" + i.ToString();
    b.CommandName = "var_value";
    b.CommandArgument = foo;
    b.Command += Execute_Command;

    //add to panel p
    p.Controls.Add(b);

    i++;
}

private void Execute_Command(object sender, CommandEventArgs e){
    //do stuff
}

The Execute_Command method is never called. The buttons display just fine, and when I debug they have the command name and the correct command argument assigned to them. I'm not sure what I'm doing wrong.

Win
  • 61,100
  • 13
  • 102
  • 181
Skettenring
  • 193
  • 1
  • 13

1 Answers1

0

Buttons are created dynamically, so they are not in the control tree. As the result, when you trigger a click event, it could not fire Command event.

In order to fix it, you will need to reload the dynamically created buttons in Page_Init or Page_Load event on every postback with same IDs.

For example,

protected void Page_Init(object sender, EventArgs e)
{
   int i = 0;
   foreach(var foo in bar){
      Button b = new Button();
      b.ID = "button" + i.ToString();
      b.CommandName = "var_value";
      .CommandArgument = foo;
      b.Command += Execute_Command;

      //add to panel p
      p.Controls.Add(b);

      i++;
   }
}
Win
  • 61,100
  • 13
  • 102
  • 181