2011-12-21 5 views
4

나는 응용 프로그램을 만들려고 노력했다. 내가 masterpage을 가지고, 내 ASP : 콘텐츠가 여기에 있습니다 : 나는 두 개의 텍스트 상자를 추가 할FindControl() return null

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
<asp:ScriptManager ID="scriptManager1" runat="server"> 
</asp:ScriptManager> 
<div style="margin: 10px"> 
    <asp:UpdatePanel ID="updatePanel1" runat="server"> 
     <ContentTemplate> 
      <asp:PlaceHolder runat="server" ID="myPlaceHolder" /> 
     </ContentTemplate> 
     <Triggers> 
      <asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" /> 
     </Triggers> 
    </asp:UpdatePanel> 
</div> 
<asp:Button ID="btnAdd" runat="server" Text="Add" /> 

btnAdd에서 클릭하십시오.

static int myCount = 1; 
    private TextBox[] color; 
    private TextBox[] text; 

    protected override void OnInit(EventArgs e) 
    { 
     base.OnInit(e); 
     color = new TextBox[myCount]; 
     text = new TextBox[myCount]; 

     for (int i = 0; i < myCount; i++) 
     { 
      TextBox tbColor = new TextBox(); 
      tbColor.ID = "colorTextBox" + i.ToString(); 
      myPlaceHolder.Controls.Add(tbColor); 
      color[i] = tbColor; 

      TextBox tbText = new TextBox(); 
      tbText.ID = "textTextBox" + i.ToString(); 
      myPlaceHolder.Controls.Add(tbText); 
      text[i] = tbText; 

      LiteralControl literalBreak = new LiteralControl("<br />"); 
      myPlaceHolder.Controls.Add(literalBreak); 
     } 
    } 


    public Control GetPostBackControl(Page page) 
    { 
     Control control = null; 
     string ctrlname = page.Request.Params.Get("__EVENTTARGET"); 
     if (ctrlname != null && ctrlname != string.Empty) 
     { 
      control = page.FindControl(ctrlname); 
     } 
     else 
     { 
      foreach (string ctl in page.Request.Form) 
      { 
       Control mycontrol = page.FindControl(ctl); 
       if (mycontrol is System.Web.UI.WebControls.Button) 
       { 
        control = mycontrol; 
        // This gives you ID of which button caused postback       
        break; 
       } 
      } 
     } 
     return control; 
    } 

    protected void Page_PreInit(object sender, EventArgs e) 
    { 
     Control myControl = GetPostBackControl(this.Page); 
     if (myControl != null) 
      if (myControl.ClientID.ToString() == "btnAdd") 
       myCount = myCount + 1; 
    } 

    protected void btnAdd_Click(object sender, EventArgs e) 
    { 
     //handled in PreInit  

    } 

때 기능 GetPostBackControl에서() loap의 foreach는 내 btnAdd을 찾고, ctl00 $ MainContent $ scriptManager1 "클릭률 (CTR)에 대한 첫 번째 반복 예를 들면 : 나는 http://jagdeepmankotia.wordpress.com/2010/01/30/dynamically-add-controls-in-asp-net-c/

이 내 코드처럼 그것을 시도해도 ", myControl은 null입니다 ... 다음 반복에서도 ... 그래서 내 함수는 항상 null을 반환합니다. 이유가 무엇일까요?

답변

8

FindControl은 컨테이너의 직접적인 하위 항목 만 검색합니다. 페이지 수준에서 시작하기 때문에 자녀의 UpdatePanel 컨트롤을 통해 재귀하여 btnAdd 컨트롤로 이동해야합니다.

예제 수행 방법은 here입니다.

편집 :이 방식에서 버튼 '을 찾고'왜 화면에 하나의 정적 버튼이 있기 때문에 내가 이해 확실하지 않다 - 당신은이에 FindControl를 사용할 필요가 없습니다 것입니다 케이스.

<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" /> 

(또는 코드에서 btnAdd.OnClick += new EventHandler(btnAdd_Click);)

는했다하더라도 양식에 여러 개의 버튼은이 경우 sender 것, 같은 버튼을 클릭 핸들러까지 그들 모두를 연결할 수 동적으로 추가 클릭 된 Button 컨트롤을 포함합니다. 일반적으로 FindControl을 사용하면 포스트 백이 발생하는 컨트롤 (적절한 이벤트 처리기에서 '보낸 사람'으로 쉽게 처리 할 수 ​​있음)을 확인하는 대신 동적으로 추가 된 입력 컨트롤 (텍스트 상자 등)에서 데이터를 긁어 내면 FindControl을 사용하게됩니다. 편집 2 : 당신은 당신이 포스트 백 사이에서 '숙박'에 이미 추가 한 모든 컨트롤을 원하는 경우 다음 페이지와의 viewstate가 가능

Button myButton = new Button(); 
    myButton.Text = "Click Me"; 
    myButton.Click += new EventHandler(btnAdd_Click); 
    myPlaceHolder.Controls.Add(myButton); 

당신은 동적으로 당신의 다른 컨트롤과 같은 버튼을 추가 할 수 있습니다 컨트롤을 선택한 다음 포스트 백없이 컨트롤을 OnInit에 한 번만 추가해야합니다.

base.OnInit(e);  
    if (!IsPostBack) 
    { // ... Add controls here 

'mycount'상태를 숨겨진 필드 (동일한 updatepanel 및 viewstate가 활성화 된 상태)에 유지할 수 있습니다. 매번 int로 구문 분석해야합니다. 또는 SessionState를 사용하여 추적 할 수 있습니다.

+0

답장을 보내 주셔서 감사합니다. 나중에 여기에 두 번째 정적 버튼을 추가합니다. 동적으로 여기에만 텍스트 상자가 표시됩니다. 그래서 내가 여기 btnAdd_Click()을 사용할 수 있다고 생각하니? myCount를 증가시키고 나중에 myCount에서 새로운 값으로 페이지를 다시로드하려면 어떻게해야합니까? 당신은 무엇을 생각합니까? – cadi2108