占位符控件计数始终在按钮单击时返回0

时间:2013-04-18 06:24:20

标签: c# asp.net placeholder

我使用下面的代码动态创建了一些TextBox,并在此TextBox中输入了一些文本。现在我想在将文本添加到数据库时读取此控件的ID。如何通过单击按钮获取此TextBox的ID。

for (int i = 0; i < dv_count; i++)
{
    TextBox txt_box = new TextBox();
    txt_box.Text = "";
    txt_box.ID = "s" + i;
    placeholder1.Controls.Add(txt_box);
}

protected void btn_act_proceed_Click(object sender, EventArgs e)
{
    int count = placeholder1.Controls.Count; //always return 0

    if (count > 0)
    {
        int dv_count = count / 2;

        for (int i = 0; i < dv_count; i++)
        {
            TextBox  lbl_type = (TextBox )placeholder1.FindControl("s" + i);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

试试这个

Aspx 页面

<div runat="server" id="plcholder">
</div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

现在位于代码

之后
protected void Page_Load(object sender, EventArgs e)
{
    populate();
}

public void populate()
{
    for (int i = 0; i < 3; i++)
    {
        TextBox tb = new TextBox();
        tb.ID = "s" + i;
        tb.Text = "Hello" + i;
        plcholder.Controls.Add(tb);
    }
}

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

    for (int i = 0; i < cont-1; i++)
    {
        TextBox tx = (TextBox)plcholder.FindControl("s" + i);
        Response.Write(tx.Text);
    }
}

答案 1 :(得分:1)

postback期间将失去控制权。因此,在preinit上,您需要再次创建控件 或者您可以将控件保持在会话中并从回发中恢复。
一个很好的链接http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i
http://www.codeproject.com/Articles/502251/How-to-create-controls-dynamically-in-ASP-NET-and

答案 2 :(得分:0)

我没有看到你首先在占位符中添加控件。试试这个

for (int i = 0; i < dv_count; i++)
{
    TextBox txt_box = new TextBox();
    txt_box.Text = "";
    txt_box.ID = "s" + i;
    placeholder1.Controls.Add(txt_box);
}

TextBox lbl_type = (TextBox)placeholder1.FindControl("s" + i);