简体   繁体   English

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

[英]get values from dynamically added textboxes asp.net c#

as suggested in the title i have in which i can insert how many textboxes i want to add to a placeholder. 如标题中所建议的,我可以在其中插入要添加到占位符的文本框的数量。 i can add the textboxes just fine the problem is i cant get the values inserted on those dynamically added textboxes. 我可以添加文本框就好了,问题是我无法在那些动态添加的文本框上插入值。 here's my code 这是我的代码

the purpose of this piece of code is to whenever the textbox in which i can introduce the number of textboxes i want. 这段代码的目的是让我可以在其中引入所需文本框数量的文本框。 it creates and adds them to the placeholder in my page. 它会创建并将它们添加到我页面中的占位符。

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

this is the code of the button that will submit and response.write the values inserted in all those textboxes. 这是将提交并响应的按钮的代码。编写在所有这些文本框中插入的值。

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

i've been searching online and i've been getting answers that this code is fine and it should work but it doesnt. 我一直在网上搜索,并且得到的答案是该代码很好,应该可以,但是没有。 if you guys see anything wrong or have any suggestion that can solve my problem i'd really appreciate it 如果你们发现任何错误或有任何建议可以解决我的问题,我将不胜感激

You are almost there. 你快到了。

Problem 问题

You need to reload those dynamically created textboxes on post back. 您需要在回发时重新加载那些动态创建的文本框。 Otherwise, they will become null, and you won't be able to find it. 否则,它们将为null,您将无法找到它。

In order to do that, you need to save those dynamically TextBoxes Ids in persistent location such as View State or Session State. 为此,您需要将这些动态TextBoxes ID保存在诸如视图状态或会话状态之类的持久位置中。

Screen Shot 屏幕截图

在此处输入图片说明

ASPX 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"/>

Code Behind 背后的代码

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

You are actually creating textboxes with property Text set to default = ""; 您实际上是在创建文本框,并将文本属性设置为default =“”; So you need set txt.Text property for example: 因此,您需要设置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);

        }
    }

EDIT: 编辑:

After that you can store your values into the list: 之后,您可以将值存储到列表中:

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

EDIT: Here is your values: 编辑:这是您的价值观: 在此处输入图片说明

EDIT: For super mega better understanding: Create one more textbox txtOutput then add button GetDataFromTextBoxesAndPutItBelow and create an event for that button `Click'. 编辑:为超级更好的理解:创建另一个文本框txtOutput然后添加按钮GetDataFromTextBoxesAndPutItBelow并为该按钮“单击”创建一个事件。 Event code: 事件代码:

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

Screenshot looks: 屏幕截图看起来: 屏幕2

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM