从动态添加的文本框中获取值asp.net c#

aco*_*cio 7 c# asp.net textbox dynamically-generated

正如我所拥有的标题所示,我可以在其中插入我想要添加到占位符的文本框的数量.我可以添加文本框就好了问题是我无法在动态添加的文本框中插入值.这是我的代码

这段代码的目的是每当文本框中我可以介绍我想要的文本框的数量.它创建并将它们添加到我的页面中的占位符.

public void txtExtra_TextChanged(object sender, EventArgs e)
{  
    for (a = 1; a <= int.Parse(txtExtra.Text); a++)
    {
         TextBox txt = new TextBox();
         txt.ID = "txtquestion" + a;
         pholder.Controls.Add(txt);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是将提交和响应的按钮的代码.写入插入所有这些文本框中的值.

protected void btnConfirm_Click(object sender, EventArgs e)
{
     foreach (Control ctr in pholder.Controls)
     {
         if (ctr is TextBox)
         {        
              string value = ((TextBox)ctr).Text;
              Response.Write(value);  
         } 
     }
 }
Run Code Online (Sandbox Code Playgroud)

我一直在网上搜索,我一直在得到这个代码很好的答案,它应该工作,但它没有.如果你们看到任何错误或有任何建议可以解决我的问题,我真的很感激

Win*_*Win 4

你快到了。

问题

您需要在回发时重新加载那些动态创建的文本框。否则,它们将变为空,并且您将无法找到它。

为此,您需要将这些动态文本框 ID 保存在持久位置,例如视图状态或会话状态。

截屏

在此输入图像描述

ASPX

Number of TextBoxes: <asp:TextBox runat="server" ID="CounterTextBox" 
    OnTextChanged="CounterTextBox_TextChanged" AutoPostBack="True" /><br/>
<asp:PlaceHolder runat="server" ID="TextBoxPlaceHolder" /><br/>
<asp:Button runat="server" ID="ConfirmButton" Text="Confirm" 
    OnClick="ConfirmButton_Click" /><br/>
Result: <asp:Literal runat="server" ID="ResultLiteral"/>
Run Code Online (Sandbox Code Playgroud)

代码隐藏

private List<string> TextBoxIdCollection
{
    get
    {
        var collection = ViewState["TextBoxIdCollection"] as List<string>;
        return collection ?? new List<string>();
    }
    set { ViewState["TextBoxIdCollection"] = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    foreach (string textboxId in TextBoxIdCollection)
    {
        var textbox = new TextBox {ID = textboxId};
        TextBoxPlaceHolder.Controls.Add(textbox);
    }
}

protected void CounterTextBox_TextChanged(object sender, EventArgs e)
{
    var collection = new List<string>();
    int total;
    if (Int32.TryParse(CounterTextBox.Text, out total))
    {
        for (int i = 1; i <= total; i++)
        {
            var textbox = new TextBox { ID = "QuestionTextBox" + i };
            // Collect this textbox id
            collection.Add(textbox.ID); 
            TextBoxPlaceHolder.Controls.Add(textbox);
        }
        TextBoxIdCollection= collection;
    }
}

protected void ConfirmButton_Click(object sender, EventArgs e)
{
    foreach (Control ctr in TextBoxPlaceHolder.Controls)
    {
        if (ctr is TextBox)
        {
            string value = ((TextBox)ctr).Text;
            ResultLiteral.Text += value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)