C# - 如何在按钮单击时动态添加和删除多个控件

时间:2017-03-14 07:52:23

标签: c#

我正在尝试编写一个调查应用程序,该应用程序需要动态添加和删除文本框。我设法动态创建文本框按钮单击,但我试图找出如何动态删除文本框。目前,删除功能只有在我从上一个开始删除文本框时才能正常工作。当我尝试删除中间的任何文本框,然后删除最后一个文本框时,会创建一个空白文本框。我是编程新手,不确定这是否是最佳使用方法。另外,我想知道是否可以嵌套文本框(允许用户向多选题添加选项)到创建文本框并在以后检索值。

代码背后:

public partial class Dynamic_Form : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < TotalNumberAdded; ++i)
        {
            AddQuestion(i + 1);
        }
    }
    protected int TotalNumberAdded
    {
        get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
        set { ViewState["TotalNumberAdded"] = value; }
    }


    protected void btn_add_Click(object sender, EventArgs e)
    {
        TotalNumberAdded++;
        AddQuestion(TotalNumberAdded);
    }

    private void AddQuestion(int controlNumber)
    {
        Panel newquestion = new Panel();
        newquestion.ID = "Panel_" + controlNumber;

        TextBox questionbox = new TextBox();
        questionbox.ID = "Question_" + controlNumber;
        questionbox.Text = "Question";

        Button BtnDelete = new Button();
        BtnDelete.ID = "BtnDelete_" + controlNumber;
        BtnDelete.Text = "Delete"+ controlNumber;
        BtnDelete.Click += delete_Click;

        DropDownList DDLType = new DropDownList();
        DDLType.ID = "DDLType_" + controlNumber;
        DDLType.Items.Insert(0, new ListItem("TextField", ""));
        DDLType.Items.Insert(1, new ListItem("Multiple Choice", ""));

        //add controls
        questions.Controls.Add(newquestion);
        newquestion.Controls.Add(questionbox);
        newquestion.Controls.Add(DDLType);
        newquestion.Controls.Add(BtnDelete);
    }

    private void delete_Click(object sender,EventArgs e)
    {
        Button btn = (Button)sender;
        Control control = btn.Parent;

        if (questions.Controls.Contains(control))
        {
            questions.Controls.Remove(control);
            control.Dispose();
            TotalNumberAdded--;
            Response.Write("Number of Questions:" + TotalNumberAdded);
        }
    }
}

Html文件:

<body>
<form id="form1" runat="server">
    <div>
        <h1>Test Form</h1>
        <asp:Button ID="btn_add" runat="server" Text="Add" OnClick="btn_add_Click" />
    </div>
    <div id="questions" runat="server">
    </div>
</form></body>