动态创建TextBoxes,每次用户单击按钮时添加一个

时间:2014-01-29 19:57:35

标签: c# asp.net textbox

我正在尝试在ASP.NET中动态创建TextBoxes,我的代码没有像我期望的那样工作......

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public int TextBoxCount
{
    get
    {
        if (ViewState["tbCount"] == null)
        {
            ViewState["tbCount"] = 0;
        }
        return Convert.ToInt32(ViewState["tbCount"]);
    }
    set
    {
        int viewState = TextBoxCount;
        if (Int32.TryParse(value.ToString(), out viewState))
        {
            ViewState["tbCount"] = value;
        }
    }
}

protected void Page_Init(object sender, EventArgs e)
{
    if (TextBoxCount == 0)
    {
        AddTextBox();
    }
    else
    {
        RecreateTextBoxes();
    }
}

private void AddTextBox()
{
    TextBox tb = new TextBox();
    tb.ID = "tb" + TextBoxCount++;
    Panel1.Controls.Add(tb);
}

private void RecreateTextBoxes()
{
    for (int i = 0; i < TextBoxCount; i++)
    {
        TextBox tb = new TextBox();
        tb.ID = "tb" + i;
        Panel1.Controls.Add(tb);
    }
}

protected void btnAdd_Click(object sender, EventArgs e)
{
    AddTextBox();
}


protected void btnDisplayText_Click(object sender, EventArgs e)
{
    for (int i = 0; i < TextBoxCount; i++)
    {
        TextBox tb = (TextBox)Page.FindControl("Panel1").FindControl("tb" + i);

        if (tb != null)
        {
            lblText.Text += "," + tb.Text;
        }
    }
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblText" runat="server" />
<div>
    <asp:Panel ID="Panel1" runat="server">
    </asp:Panel>
</div>
<asp:Button ID="btnDisplayText" runat="server" Text="Display Text" onclick="btnDisplayText_Click" />
<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />
</form>
</body>
</html>

我想要做的是每次用户点击btnAdd按钮时动态创建一个新的TextBox。然后,btnDisplayText按钮应连接每个TextBox中的所有文本,并将其显示在lblText中。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

使用

TextBox tb = (TextBox)Panel1.FindControl("tb" + i);

而不是

TextBox tb = (TextBox)Page.FindControl("Panel1").FindControl("tb" + i);
btnDisplayText_Click中的

此外,从ViewState["tbCount"] = value; setter。

中删除TextBoxCount以外的所有代码

<强>更新

<{1}}中未提供

ViewState。将您的Page_Init代码移至Page_Init

答案 1 :(得分:0)

int TextBoxID=0;
TextBox textBox = new TextBox();

TextBox.ID="TextBox"+TextBoxID.ToString();

btnDisplayText.Text +=textBox.Text;

lblText.Text=btnDisplayText.Text;

TextBoxID++;