2014-06-29 156 views
0

給定多個動態創建的文本框,我想獲取用戶填充的文本。 我用一個面板和創作作品。找不到文本框的控件。從動態創建文本框中獲取文本值

ASPX

<div> 
    <asp:Panel ID="Panel1" runat="server"></asp:Panel> 
</div> 
<div> 
    <asp:Button ID="Button1" runat="server" Text="Adauga autor" OnClick="Button1_Click" /> 
</div> 

創建文本框

protected void Button1_Click(object sender, EventArgs e) 
{ 
    int rowCount = Convert.ToInt32(Session["clicks"]); 
    rowCount++; 
    Session["clicks"] = rowCount; 

    for (int i = 1; i <= rowCount; i++) 
    { 
     TextBox TxtBoxA = new TextBox(); 
     Label lblA = new Label(); 

     TxtBoxA.ID = "TextBoxA" + i.ToString(); 
     lblA.ID = "LabelA" + i.ToString(); 
     lblA.Text = "Label" + i.ToString() + ": "; 

     Panel1.Controls.Add(lblA); 
     Panel1.Controls.Add(TxtBoxA); 
     Panel1.Controls.Add(new LiteralControl("<br />")); 
    } 
} 

獲取文本

int rowCount = Convert.ToInt32(Session["clicks"]); 
for (int i = 1; i <= rowCount; i++) 
{ 
    string item = "TextBoxA" + i.ToString(); 
    Control foundControl = FindControl(item, Page.Controls); 
    TextBox TB = (TextBox)foundControl; 
    string txt = TB.Text; 
} 

+

public static Control FindControl(string controlId, ControlCollection controls) 
{ 
    foreach (Control control in controls) 
    { 
     if (control.ID == controlId) 
      return control; 

     if (control.HasControls()) 
     { 
      Control nestedControl = FindControl(controlId, control.Controls); 

      if (nestedControl != null) 
       return nestedControl; 
     } 
    } 
    return null; 
} 

文本框控件爲空。我究竟做錯了什麼?

+0

在哪裏_ 「獲取文本」 _在哪裏?您最遲必須在'Page_Load'中重新創建所有控件。 'Button1_Click'稍後。 –

+0

string txt = TB.Text;但爲什麼Page_Load?我只需要在Button1_Click輸入後才需要文本。 – Kevin

+0

您必須在'Page_init'或'Page_Load'中重新創建所有動態創建的控件,稍後(如事件處理程序)爲'ViewState'後期_too_等。此外,您的遞歸「FindControl」是不必要的。在控件的「NamingContainer」中使用「普通」FindControl。既然你不使用實現'INamingContainer'(比如'GridView)'的控件,你可以簡單地使用'Page.FindControl(..)'。 –

回答

0

您必須最遲在Page_Load中重新創建所有控件。 Button1_Click爲時已晚。因此,請在Page_Init/Page_Load中重新創建Session["clicks"],並在Button-Click-處理程序中創建單個新控件。

一些代碼:

protected void Page_Init(Object sender, EventArgs e) 
{ 
    RecreateControls(); 
} 

private void RecreateControls() 
{ 
    int rowCount = Convert.ToInt32(Session["clicks"]); 
    CreateControls(rowCount); 
} 

private void AddControl() 
{ 
    int rowCount = Convert.ToInt32(Session["clicks"]); 
    CreateControls(1); 
    Session["clicks"] = rowCount++; 
} 

private void CreateControls(int count) 
{ 
    for (int i = 1; i <= count; i++) 
    { 
     TextBox TxtBoxA = new TextBox(); 
     Label lblA = new Label(); 

     TxtBoxA.ID = "TextBoxA" + i.ToString(); 
     lblA.ID = "LabelA" + i.ToString(); 
     lblA.Text = "Label" + i.ToString() + ": "; 

     Panel1.Controls.Add(lblA); 
     Panel1.Controls.Add(TxtBoxA); 
     Panel1.Controls.Add(new LiteralControl("<br />")); 
    } 
} 

protected void Button1_Click(object sender, EventArgs e) 
{ 
    AddControl(); 
}