2016-11-10 5 views
2

asp.net 웹 응용 프로그램에 x 개의 숫자 버튼을 추가하고 있습니다. 이것은 내 코드입니다.동적으로 추가 된 ASP.Net 단추가 Click 또는 CommandArgument 이벤트를 호출하지 못했습니다.

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 
} 

Execute_Command 메소드는 절대로 호출되지 않습니다. 버튼은 정상적으로 표시되며 디버깅 할 때 명령 이름과 올바른 명령 인수가 할당됩니다. 내가 뭘 잘못하고 있는지 모르겠다.

답변

0

버튼이 동적으로 만들어 지므로 버튼이 컨트롤 트리에 없습니다.. 결과적으로 클릭 이벤트를 트리거 할 때 Command 이벤트를 발생시킬 수 없습니다.

은 문제를 해결하기 위해, 당신은동일한 ID를모든 포스트 백에 후 Page_Init 또는 를 Page_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++; 
    } 
} 
+0

이 일했다! 이 코드를 포함하는 메소드는 if (! IsPostBack) 내에서 호출되었습니다. 감사합니다! – Skettenring