Ninjutstu Ninjutstu - 26 days ago 11
ASP.NET (C#) Question

C# button using CommandArgument will not call method

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 Win
Answer

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++;
   }
}