2016-11-28 42 views
0

我使用ASP Panel在按鈕單擊時動態創建文本框。我使用的代碼如下,ASP.NET動態創建使用asp:Panel的文本框並使用FindControl訪問文本框

<asp:TextBox ID="text_number" runat="server"></asp:TextBox> 
<asp:Button ID="button1" runat="server" OnClick="button1_Click"></asp:Button> 
<asp:Panel ID="mypanel" runat="server"></asp:Panel> 
<asp:Button ID="button2" runat="server" OnClick="button2_Click"></asp:Button> 


protected void button1_Click(object sender, EventArgs e) 
{ 
    int n = Convert.ToInt32(text_number.Text); 
    for (int i = 0; i < n; i++) 
    { 
     TextBox MyTextBox = new TextBox(); 
     MyTextBox.ID = "newtext_" + (i + 1); 
     mypanel.Controls.Add(MyTextBox); 
     MyTextBox.CssClass = "textblock"; 
     Literal lit = new Literal(); 
     lit.Text = "<br />"; 
     mypanel.Controls.Add(lit); 
    } 
} 

Button1的創建文本框之後我點擊,然後我輸入值的文本框,然後點擊按鈕2。當單擊button2時,應該讀取文本框中的所有值,並將其存儲在C#後面的列表中。我使用的代碼如下,

protected void button2_Click(object sender, EventArgs e) 
{ 
    int n = Convert.ToInt32(text_number.Text); 
    for (int i = 0; i < n; i++) 
    { 
     TextBox control = (TextBox) FindControl("newtext_" + (i+1)); 
     mylist.Add(control.Text); 
    } 
} 

但每當我在BUTTON2點擊,所有的文本框我在面板中添加從網頁上消失,還我得到空對象引用錯誤中的FindControl 。我可以理解,當按下按鈕2時,面板中的所有文本框控件都會被清除,這就是它們在網頁中消失的原因,也是獲取空對象錯誤的原因。這裏有什麼問題?有沒有其他的方式來動態創建按鈕點擊'n'文本框,然後從第二個按鈕點擊他們獲取值沒有這樣的問題?

回答

0

由於您正在動態創建控件,因此您需要在每次頁面加載時接收它們,否則控件及其內容將會丟失。

你需要做的是將文本框的數量存儲到SessionViewState並重新創建它們。

protected void Page_Load(object sender, EventArgs e) 
{ 
    //check if the viewstate exists and if so, build the controls 
    if (ViewState["boxCount"] != null) 
    { 
     buildControls(Convert.ToInt32(ViewState["boxCount"])); 
    } 
} 

protected void button1_Click(object sender, EventArgs e) 
{ 
    //adding controls moved outside the button click in it's own method 
    try 
    { 
     buildControls(Convert.ToInt32(text_number.Text)); 
    } 
    catch 
    { 
    } 
} 

protected void button2_Click(object sender, EventArgs e) 
{ 
    //check if the viewstate exists and if so, build the controls 
    if (ViewState["boxCount"] != null) 
    { 
     int n = Convert.ToInt32(ViewState["boxCount"]); 

     //loop al controls count stored in the viewstate 
     for (int i = 0; i < n; i++) 
     { 
      TextBox control = FindControl("newtext_" + i) as TextBox; 
      mylist.Add(control.Text); 
     } 
    } 
} 

private void buildControls(int n) 
{ 
    //clear the panel of old controls 
    mypanel.Controls.Clear(); 

    for (int i = 0; i < n; i++) 
    { 
     TextBox MyTextBox = new TextBox(); 
     MyTextBox.ID = "newtext_" + i; 
     MyTextBox.CssClass = "textblock"; 
     mypanel.Controls.Add(MyTextBox); 

     Literal lit = new Literal(); 
     lit.Text = "<br />"; 
     mypanel.Controls.Add(lit); 
    } 

    //save the control count into a viewstate 
    ViewState["boxCount"] = n; 
}