2016-11-28 84 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; 
}