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.

4

1 回答 1

0

按钮是动态创建的,因此它们不在控件树中。结果,当您触发点击事件时,它无法触发 Command 事件。

为了修复它,您需要在每次回发时使用相同的 ID重新加载Page_InitPage_Load事件中动态创建的按钮。

例如,

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++;
   }
}
于 2016-11-10T20:45:56.610 回答