如何从占位符获取所有文本框? asp.net c#网络表单

时间:2019-02-06 19:20:48

标签: c# asp.net dynamic webforms controls

我的html上有一个asp:placeholder,我正在访问它以添加用于回答问题和答案的文本框和标签。

正确创建了“表单”,我得到了所有带有问题的标签和每个答案的文本框,但是当我单击按钮后,单击runatserver时,Placeholder1始终为空。

我尝试了很多事情来获取文本框值,以便在没有运气的情况下插入数据库。

在我的代码下面。

谢谢您的帮助。

网络表单中表单的HTML代码:

/* form for the buttons and title*/

<form id="form2" runat="server">

    <div align="center">
    </div>
    <div>
        <div align="center" class="form-group">
            <h4>
                <asp:label runat="server" id="title"></asp:label>
            </h4>
            <br />
            <br />
            <div align="center">
                place holder for the questions&answers

                    <asp:placeholder id="Placeholder1" runat="server">
                    </asp:placeholder>
            </div>
        </div>
    </div>
    <br />
    <br />

C#代码获取多少个问题,然后为每个答案添加一个文本框,并使用带有计数器的cicle来添加id + counter

/* c# a counter is made to increment a number to the id*/

Adding controls to the PlaceHolder1     
/* add controls: */

在计数器内为sqlresult的所有行数添加标签* /

标签

Label quest= new Label();
quest.ID = "quest" + counter;
quest.Attributes.Remove("class");
quest.Attributes.Add("class", "exampleFormControlInput1");

quest.text = "sql query";

文本框        / 在提示处添加文本框 /

TextBox answer = new TextBox();
answer .ID = "answer " + counter;
answer .Attributes.Remove("class");
answer .Attributes.Add("class", "form-control");

PlaceHolder1.Controls.Add(quest);
PlaceHolder1.Controls.Add(new LiteralControl("<br>"));
PlaceHolder1.Controls.Add(answer);
PlaceHolder1.Controls.Add(new LiteralControl("<br>"));

检查PlaceHolder1内部有多少个控件

尝试检查PlaceHolder1中有多少个控件

count = PlaceHolder1.Controls.Count;

总是0

1 个答案:

答案 0 :(得分:0)

您可能没有在PostBack上重新创建控件。请参阅此工作示例。

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack == false)
    {
        //do not create controls here
    }

    for (int count = 0; count < 5; count++)
    {
        TextBox answer = new TextBox();
        answer.ID = "answer " + count;
        PlaceHolder1.Controls.Add(answer);
    }
}

然后在PostBack上

protected void Button1_Click(object sender, EventArgs e)
{
    int count = PlaceHolder1.Controls.Count;

    for (int i = 0; i < count; i++)
    {
        TextBox answer = PlaceHolder1.FindControl("answer " + i) as TextBox;
        Label1.Text += answer.Text + "<br>";
    }
}
相关问题