2011-07-31 10 views
2

질문은 요즘 나를 괴롭 히고 있습니다. 네가 나를 도왔 으면 좋겠어.동적으로 생성 된 버튼을 동적으로 생성 된 테이블에 추가하는 방법은 무엇입니까?

사용자가 단추를 클릭 한 후에 표를 만들고 싶습니다. 첫 번째 셀의 각 행에서 버튼을 추가하고 싶습니다. 불행하게도, 테이블 버튼은 이벤트를 발생시키지 못합니다. 그것을하는 방법 또는 나의 실수가있는 곳을 말해 줄 수 있습니까? this article을 사용하여 다음 예제 코드를 생성했습니다.

<asp:PlaceHolder ID="placeHolderForTable" runat="server"> 

</asp:PlaceHolder> 
<asp:Button ID="btnCreateTbl" runat="server" Text="Create Table"/> 
<asp:Label ID="lblResult" runat="server" /> 

코드 :

private struct ControlInfo 
{ 
    public string ID; 
    public string Type; 
    public int Border; 
    public HtmlTableRow[] TblRows; 
    public HtmlTableCell[] TblCells; 
    public int Width; 
    public int Height; 
} 


protected void Page_Load(object sender, EventArgs e) 
{ 
    btnCreateTbl.Click+=new EventHandler(BtnClick); 
    if (this.IsPostBack) this.RecreatePersistedControls(); 
}//end Page_Load 


//Call CreateControl for each persisted control 
private void RecreatePersistedControls() 
{ 
    ArrayList al = (ArrayList)this.Session["DynamicControls"]; 
    if (al != null) 
     foreach (ControlInfo ci in al) 
      this.CreateControl(ci); 
}//end RecreatePersisterdControls method 

//Create control specified by ControlInfo structure 
private Control CreateControl(ControlInfo ci) 
{ 
    Control ctl = null; 

    switch (ci.Type) 
    { 
     case "Button": 
      ctl = new Button(); 
      ctl.ID = ci.ID; 
      ((Button)ctl).Text = "Edit"; 
      ((Button)ctl).Click+=new EventHandler(this.DoNothing); 
      if (this.placeHolderForTable.FindControl("tblResult") != null) 
      { 
       for (int r = 0; r < ci.Height; r++) 
       { 
        if (this.placeHolderForTable.FindControl("tblResult").FindControl("tr" + (r + 1)) != null && (r+1).ToString()==ci.ID[7].ToString()) 
         if (this.placeHolderForTable.FindControl("tblResult").FindControl("tr" + (r + 1)).FindControl("td" + (r + 1) + "1") != null) 
          if(this.placeHolderForTable.FindControl("tblResult").FindControl("tr" + (r + 1)).FindControl("td" + (r + 1) + "1").FindControl(ctl.ID)==null) 
           this.placeHolderForTable.FindControl("tblResult").FindControl("tr" + (r + 1)).FindControl("td" + (r + 1) + "1").Controls.Add(ctl); 
       } 
      } 
      break; 
     case "HtmlTable": 
      ctl = new HtmlTable(); 
      ctl.ID = ci.ID; 
      ((HtmlTable)ctl).Border = ci.Border; 

      for (int r = 0; r < ci.Height; r++) 
      { 
       HtmlTableRow row = ci.TblRows[r]; 
       row.ID = "tr" + (r + 1); 
       for (int c = r * ci.Width; c < r * ci.Width+2; c++) 
       { 
        ci.TblCells[c].ID="td"+(r+1)+(c%2+1); 
        row.Cells.Add(ci.TblCells[c]); 

       } 
       ((HtmlTable)ctl).Rows.Add(row); 
      } 
      if(this.placeHolderForTable.FindControl(ctl.ID)==null) 
       this.placeHolderForTable.Controls.Add(ctl); 
      break; 
     default: 
      return null; 
    } 
    return ctl; 
}//end CreateControl method 

//Create ControlInfo structure and persist it to Session 
private ControlInfo PersistControl(string id, string type, int border, HtmlTableRow[] tblRows, HtmlTableCell[] tblCells, int width, 
    int height) 
{ 
    ControlInfo ci = new ControlInfo(); 
    ci.ID = id; 
    ci.Type = type; 
    ci.Border = border; 
    ci.TblRows = tblRows; 
    ci.TblCells = tblCells; 
    ci.Width = width; 
    ci.Height = height; 

    ArrayList al = (ArrayList)this.Session["DynamicControls"]; 
    if (al == null) al = new ArrayList(); 
    al.Add(ci); 
    this.Session["DynamicControls"] = al; 
    return ci; 
}//end PersistControl method 

private void BtnClick(object sender, EventArgs e) 
{ 
    int cellIx=0,rowIx=0;    
    HtmlTableRow tr1 = new HtmlTableRow(); 
    HtmlTableCell td11 = new HtmlTableCell(); 
    tr1.Cells.Add(td11); 
    HtmlTableCell td12 = new HtmlTableCell(); 
    td12.InnerText = "td12"; 
    tr1.Cells.Add(td12); 
    HtmlTableRow tr2 = new HtmlTableRow(); 
    HtmlTableCell td21 = new HtmlTableCell(); 
    tr2.Cells.Add(td21); 
    HtmlTableCell td22 = new HtmlTableCell(); 
    tr2.Cells.Add(td22); 
    td22.InnerText = "td22"; 
    HtmlTableRow []arrRows=new HtmlTableRow[2]; 
    arrRows[rowIx++]=tr1; 
    arrRows[rowIx++]=tr2; 
    HtmlTableCell []arrCells=new HtmlTableCell[4]; 
    arrCells[cellIx++]=td11; 
    arrCells[cellIx++]=td12; 
    arrCells[cellIx++]=td21; 
    arrCells[cellIx++]=td22; 
    ControlInfo ci = PersistControl("tblResult", "HtmlTable", 3, arrRows, arrCells, 2, 2); 
    HtmlTable tblResult = (HtmlTable)CreateControl(ci); 

    ci = PersistControl("btnEdit1", "Button", 0, arrRows, arrCells, 2, 2); 
    Button btnEdit1 = (Button)CreateControl(ci); 

    ci = PersistControl("btnEdit2", "Button", 0, arrRows, arrCells, 2, 2); 
    Button btnEdit2 = (Button)CreateControl(ci); 
} 

public void DoNothing(object sender, EventArgs e) 
{ 
    lblResult.Text = (sender as HtmlButton).ID + " done"; 
} 
+0

저는 이것이 특별히 건설적인 의견이 아니라는 것을 알고 있습니다. 그러나이 게시물을 Microsoft가 ASP를 소개하는 것이 옳은 이유의 예로서 사용할 것입니다. NET MVC (왜 WebForms가 존재해서는 안될까?) –

+0

원하는대로 수행하십시오. – Pepe

답변

0

동적 제어가 완전히 다른 짐승이고 나는 가능한 한 많이 그들과 떨어져 유지하려고합니다. 즉, 필요한 경우가 있습니다.

이벤트 핸들러 및 동적 컨트롤에 대한 문제는, 그렇지 않으면 그들은 내가이 만든 이상하게 http://support.microsoft.com/?id=317794

를 작동 할 수 있습니다 철사와하는 OnInit 또는를 Page_Load 기능의 페이지 컨트롤 트리에 컨트롤을 추가해야 할 Page_Load에서 이벤트 핸들러를 연결하는 코드를 일부 수정합니다. 아래를보고 궁금한 점이 있으면 알려주십시오.

// Added a ViewState persisted prop 
    bool WireUpControls 
    { 
     get 
     { 
      return ViewState["wireUpControls"] != null ? Convert.ToBoolean(ViewState["wireUpControls"]) : false; 
     } 
     set 
     { 
      ViewState["wireUpControls"] = value; 
     } 
    } 

    void CreateControlTable() 
    { 
     int cellIx = 0, rowIx = 0; 
     HtmlTableRow tr1 = new HtmlTableRow(); 
     HtmlTableCell td11 = new HtmlTableCell(); 
     tr1.Cells.Add(td11); 
     HtmlTableCell td12 = new HtmlTableCell(); 
     td12.InnerText = "td12"; 
     tr1.Cells.Add(td12); 
     HtmlTableRow tr2 = new HtmlTableRow(); 
     HtmlTableCell td21 = new HtmlTableCell(); 
     tr2.Cells.Add(td21); 
     HtmlTableCell td22 = new HtmlTableCell(); 
     tr2.Cells.Add(td22); 
     td22.InnerText = "td22"; 
     HtmlTableRow[] arrRows = new HtmlTableRow[2]; 
     arrRows[rowIx++] = tr1; 
     arrRows[rowIx++] = tr2; 
     HtmlTableCell[] arrCells = new HtmlTableCell[4]; 
     arrCells[cellIx++] = td11; 
     arrCells[cellIx++] = td12; 
     arrCells[cellIx++] = td21; 
     arrCells[cellIx++] = td22; 
     ControlInfo ci = PersistControl("tblResult", "HtmlTable", 3, arrRows, arrCells, 2, 2); 
     HtmlTable tblResult = (HtmlTable)CreateControl(ci); 

     ci = PersistControl("btnEdit1", "Button", 0, arrRows, arrCells, 2, 2); 
     Button btnEdit1 = (Button)CreateControl(ci); 

     ci = PersistControl("btnEdit2", "Button", 0, arrRows, arrCells, 2, 2); 
     Button btnEdit2 = (Button)CreateControl(ci); 
    } 

    // Call CreateControlTable() if we need to create the controls and wire up events 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     btnCreateTbl.Click += new EventHandler(BtnClick); 
     if (WireUpControls) CreateControlTable(); 
     //if (this.IsPostBack) this.RecreatePersistedControls(); 

    } 

    protected void BtnClick(object sender, EventArgs e) 
    { 
     WireUpControls = true; 
     CreateControlTable(); 
    } 

    public void DoNothing(object sender, EventArgs e) 
    { 
     lblResult.Text = (sender as Button).ID + " done"; 
    } 
+0

답변 해 주셔서 감사합니다. 그러나 테이블 안의 버튼은 여전히 ​​"DoNothing"이벤트를 발생시키지 않습니다. – Pepe

+0

디버깅은 WireUpControls가 항상 "false"를 반환 함을 보여줍니다. – Pepe

+0

아하. ViewState [ "wireUpControls"]는 BtnClick 이벤트에서 (테이블의 초기 생성시) true로 설정되어야합니다. – Pepe

관련 문제