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

7

如标题所示,我有一个可以向占位符添加任意数量文本框的表单。我已经成功添加了这些文本框,但问题是我无法获取动态添加的文本框中插入的值。以下是我的代码:

这段代码的目的是,当我在文本框中输入要添加的文本框数量时,它会在页面上创建并添加它们到占位符中。

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

这是提交按钮的代码,它将提交并response.write所有文本框中插入的值。
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);  
         } 
     }
 }

我在网上搜索并得到答案说这段代码没问题应该可以运行,但实际上并不行。如果你们发现了任何问题或有任何建议可以解决我的问题,我将非常感激。


这为什么没有失败?txtExtra.text。我以为C#是区分大小写的。 - attila
那是一个错误,把它粘贴在这里了。在代码中没有问题。 - aconstancio
“粘贴”代码时改变大小写有点令人担忧。这会让回答者想知道你粘贴时改变了什么其他内容。 - attila
3个回答

4
你已经接近成功了。
问题:
在回发(post back)时需要重新加载那些动态创建的文本框,否则它们将变为空值,你将无法找到它们。
为了做到这一点,你需要将那些动态创建的文本框的Id保存在持久化位置中,例如ViewState或Session State。
屏幕截图:
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"/>

代码后台

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;
        }
    }
}

这个解决方案真的非常简单易行。xD - Wallstrider

2
你实际上是在创建Text属性设置为默认值 =“”;的文本框。因此,你需要设置txt.Text属性,例如:
    public void txtExtra_TextChanged(object sender, EventArgs e)
    {
        for (int a = 1; a <= int.Parse(txtExtra.Text); a++)
        {
            TextBox txt = new TextBox();
            txt.ID = "txtquestion" + a;
            txt.Text = "Some text"; // Set some text here
            pholder.Controls.Add(txt);

        }
    }

编辑:

之后,您可以将值存储到列表中:

private static List<string> values = new List<string>();

    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        foreach (Control ctr in pholder.Controls)
        {
            if (ctr is TextBox)
            {
                string value = ((TextBox)ctr).Text;
                values.Add(value); // add values here
            }
        }
    }

编辑: 以下是您的值: enter image description here

编辑: 为了更好地理解: 创建另一个文本框txtOutput,然后添加按钮GetDataFromTextBoxesAndPutItBelow并为该按钮创建一个事件'Click'。事件代码:

    protected void btnGetData_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < values.Count; i++)
            txtOutput.Text += "Value from txtquestion1: " + values[i] + " ";
    }

截图如下: screen2

我的目标是在创建文本框后获取其输入的值。即使我在创建时为每个文本框设置了文本,但之后也无法获取它。不知道我是否解释清楚了。 - aconstancio
List<string>的值不包含任何项?不能是xD。 - Wallstrider
当我点击按钮后没有任何反应,就像在我最初的代码中一样。 - aconstancio
你期望的是什么?我的目标是获取文本框中输入的值。你有检查过List<string> values吗?它包含了所有文本框中的值。如果集合为空,请告诉我。尝试使用断点等调试工具。 - Wallstrider
我添加了GetDataFromBoxes按钮和btnGetData_Click事件,只是为了设置断点并向您展示更好的理解截图。 - Wallstrider

0
for (int i = 0; i < dataTable.Rows.Count; i++)
{

    int comment_id = Convert.ToInt32(dataTable.Rows[i]["comment_id"]);
    string created_by_name = dataTable.Rows[i]["created_by_name"].ToString();
    string created_at = dataTable.Rows[i]["created_at"].ToString();
    string comment = dataTable.Rows[i]["comment"].ToString();

    HtmlGenericControl divComment = new HtmlGenericControl("div"); //This is root object of comment.Other objects like textbox,button,etc added into this object.
    //divComment.Attributes.Add("class", "div_post_display");
    divComment.Attributes.Add("id", comment_id.ToString());

    /* Comment by */
    HtmlGenericControl lblCommentBy = new HtmlGenericControl("label");
    //lblCommentBy.Attributes.Add("class", "divauthor");
    lblCommentBy.InnerText = "" + created_by_name + " (" + created_at + ")";

    /* Comment body */
    HtmlGenericControl pComment = new HtmlGenericControl("p");
    //lblCommentBy.Attributes.Add("class", "divauthor");
    pComment.InnerText = comment;

    divComment.Controls.Add(lblCommentBy);
    divComment.Controls.Add(pComment);

    if (Session["user_id"] != null)
    {
        if (Session["user_level"].ToString() == "1") //Admin can reply for comment
        {
            /* Reply Form */
            TextBox txtReply = new TextBox(); //Create object dynamacaly
            txtReply.ID = "txtReply_"+comment_id;
            txtReply.Attributes.Add("class", "form-control"); //Add css class
            txtReply.Width = 400;
            divComment.Controls.Add(txtReply); //Add obj to root object(div)

            Button btnReply = new Button(); //Create object dynamacaly
            btnReply.Text = "Reply"; //Set button text 
            btnReply.Attributes.Add("class", "btn btn-sm btn-success"); //Add css class
            btnReply.Click += btnReply_Click;
            btnReply.CommandArgument = comment_id.ToString();
            divComment.Controls.Add(btnReply); //Add obj to root object(div)

            HtmlGenericControl br = new HtmlGenericControl("br"); //Create object dynamacaly
            divComment.Controls.Add(br); //new line
        }
    }
    pnlShowComments.Controls.Add(divComment);

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接