1

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

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)
        {
        }
    }

谢谢,

4

2 回答 2

1

我希望这是您评论中他的要求

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

您有 2 个按钮 一个按钮可以使用 Jquery 创建 TextBox。(与回发相比,客户端脚本要快得多)。

在这里您可以看到如何使用 Jquery 添加文本框

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

另一个按钮,您可以使用 Jquery 序列化表单并将其发送到服务器。

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

处理 JSON 数据

C# JSON 自定义序列化 这将展示如何从 JSON 获取数据。

这是一种可以通过客户端脚本实现的方法,并且可能比您建议的方法运行得更快。

谢谢

于 2012-06-18T11:11:51.307 回答
0

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

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

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

TextBoxValue.Add(textBox1.Text);

但是,这会使页面变得沉重。

于 2012-06-18T10:08:06.017 回答