按钮单击动态创建文本框

时间:2013-06-09 11:46:07

标签: c# asp.net textbox

我创建了一个按钮,当单击它时,它应该连续显示3个文本框。但是,每次单击“提交”按钮时,文本框将显示2行(即6个文本框)。然后每次点击增加2行。

无论如何,它可以在每次点击时增加一行文本框?

以下是代码:

<form id="form1" runat="server">
<div>

    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    <asp:Panel ID="Panel1" runat="server">
    </asp:Panel>

</div>
</form>

代码背后:

         protected void Page_Load(object sender, EventArgs e)
       {
        // Add any controls that have been previously added dynamically
         for (int i = 0; i < TotalNumberAdded;  i++)
        {
        AddControls(i + 1);
        }

    // Attach the event handler to the button
    Button1.Click += new EventHandler(Button1_Click);
}

protected void Button1_Click(object sender, EventArgs e)
{

    // Increase the number added and add the new label and textbox
    TotalNumberAdded++;
    AddControls(TotalNumberAdded);

}

private void AddControls(int controlNumber)
{

        TextBox TxtBoxU = new TextBox();

        TextBox TxtBoxE = new TextBox();

        TextBox TxtBoxY = new TextBox();

        Label lblU = new Label();
        Label lblE = new Label();
        Label lblY = new Label();

        TxtBoxU.ID = "TextBoxU" + controlNumber;
        TxtBoxE.ID = "TextBoxE" + controlNumber;
        TxtBoxY.ID = "TextBoxY" + controlNumber;

        lblU.ID = "LabelU" + controlNumber;
        lblE.ID = "LabelE" + controlNumber;
        lblY.ID = "LabelY" + +controlNumber;

        lblU.Text = "User : ";
        lblE.Text = "E-Mail : ";
        lblY.Text = "Phone number : ";

        //Add the labels and textboxes to the Panel.
        Panel1.Controls.Add(lblU);
        Panel1.Controls.Add(TxtBoxU);
        Panel1.Controls.Add(TxtBoxU);

        Panel1.Controls.Add(lblE);
        Panel1.Controls.Add(TxtBoxE);

        Panel1.Controls.Add(lblY);
        Panel1.Controls.Add(TxtBoxY);
        Panel1.Controls.Add(new LiteralControl("<br>"));

   }

protected int TotalNumberAdded
{
    get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
    set { ViewState["TotalNumberAdded"] = value; }
}

2 个答案:

答案 0 :(得分:0)

您的问题出在页面加载中,因为click event声明是多余的,当您通过HTML进行分配时附加EventHandler,如果您按下该事件,则会触发2时间。

删除

Button1.Click += new EventHandler(Button1_Click); 

您的页面加载将如下所示:

   protected void Page_Load(object sender, EventArgs e)
   {
    // Add any controls that have been previously added dynamically
     for (int i = 0; i < TotalNumberAdded;  i++)
    {
      AddControls(i + 1);
    }

  }

我希望有所帮助。

P.S:我很抱歉在我的第一次测试中我没有正确测试。

答案 1 :(得分:0)

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox txtobj = new TextBox();
    Form.Controls.Add(txtobj);
    txtobj.Text = "Dynamically Textbox";

}