ASP.NET动态创建文本框使用asp:Panel并使用FindControl访问文本框

时间:2016-11-28 17:12:09

标签: c# html asp.net

我正在使用ASP Panel在按钮点击时动态创建文本框。我使用的代码如下,

<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后,会创建文本框,然后在文本框中输入值,然后单击button2。单击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”文本框,然后在第二次按钮单击时从中获取值,而不会出现这样的问题?

1 个答案:

答案 0 :(得分:0)

因为您正在动态创建控件,所以您需要在每次页面加载时重新加载它们,否则控件及其内容将会丢失。

您需要做的是将TextBox的数量存储到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;
}
相关问题