保留动态添加的文本框的值

时间:2012-06-18 09:50:11

标签: c# asp.net textbox

我通过按钮点击后面的代码动态添加文本框,它工作正常。在另一个按钮单击我想要获取所有动态添加的文本框的值。但是文本框的值是空的。如何在回发时保留动态添加的文本框的值?

Aspx代码

<asp:Table runat="server" id="placeAddTds">
  <asp:TableRow>

    <asp:TableCell><asp:TextBox ID="txt_from" runat="server" class="sabsw" TabIndex="88"></asp:TextBox></asp:TableCell>
    <asp:TableCell><asp:TextBox ID="txt_to" runat="server" class="sabsw" TabIndex="89"></asp:TextBox></asp:TableCell>
    <asp:TableCell><asp:TextBox ID="txt_per" runat="server" class="sabsw" TabIndex="90"></asp:TextBox></asp:TableCell>

    <asp:TableCell>
    <asp:Button class="main-btn add-btn pointer" runat="server" ID="btn_add" Text="Add" OnClick="TdsAddClick" TabIndex="91"></asp:Button>
   </asp:TableCell>
  </asp:TableRow>
  </asp:Table>

代码背后:

 protected void TdsAddClick(object sender,EventArgs e)
    {
        try
        {
            TextBox[] l1 = new TextBox[txtcount];
            TextBox[] l2 = new TextBox[txtcount];
            TextBox[] l3 = new TextBox[txtcount];
            for (int j = 1; j < txtcount; j++)
            {
                l1[j] = new TextBox();
                l2[j] = new TextBox();
                l3[j] = new TextBox();
                l1[j].ID = "txt_from" + j;
                l1[j].Attributes.Add("class","sabsw");
                l2[j].ID = "txt_to" + j;
                l2[j].Attributes.Add("class", "sabsw");
                l3[j].ID = "txt_per" + j;
                l3[j].Attributes.Add("class", "sabsw");
                placeAddTds.Rows.Add(new TableRow());
                placeAddTds.Rows[j].Cells.Add(new TableCell());
                placeAddTds.Rows[j].Cells[0].Controls.Add(l1[j]);
                placeAddTds.Rows[j].Cells.Add(new TableCell());
                placeAddTds.Rows[j].Cells[1].Controls.Add(l2[j]);
                placeAddTds.Rows[j].Cells.Add(new TableCell());
                placeAddTds.Rows[j].Cells[2].Controls.Add(l3[j]);
           }
            txtcount++;
        }
        catch (Exception ex)
        {
        }
    }

谢谢,

2 个答案:

答案 0 :(得分:1)

我希望这是你评论的要求

我有两个按钮。点击一个按钮我想动态添加文本框,点击第二个按钮我想保存数据库中所有文本框的值

你有2个按钮 您可以使用Jquery创建TextBox的一个按钮。 (与回发相比,客户端脚本速度非常快。)

Here you can see how to add text box using Jquery

因此,您可以动态添加文本框而无需回发。

Another button you can serialize the form using Jquery and send it to server.

将数据传递到服务器 它将创建一个JSON对象并将其传递给服务器。 你可以传入__doPostBack(control,args)。在args中,您可以传递JSON值。 Click Here

处理JSON数据

C# JSON custom serialization 这将显示如何从JSON获取数据。

这是一种可以使用客户端脚本实现的方法,它可能比您建议的方法快得多。

由于

答案 1 :(得分:0)

您可以在代码隐藏中为此添加ViewState属性,并将所有值存储在列表中:

private List<string> TextBoxValue
        {
            get
            {
                return (List<string>)ViewState["TextBoxValue"];
            }
            set
            {
                ViewState["TextBoxValue"] = value;
            }
        }

然后,您可以在此属性中存储文本框的值。例如:

TextBoxValue.Add(textBox1.Text);

然而,这会使页面变重。