如何一一删除以编程方式创建的控件?

时间:2018-06-24 14:06:01

标签: c# winforms datagridview

我写了一些代码来动态创建控件。这段代码工作正常,现在我想一键式删除控件。所以帮我怎么做?

 private void button1_Click_1(object sender, EventArgs e)
    {

            Label label = new Label();
            int count = panel1.Controls.OfType<Label>().ToList().Count;
            label.Location = new Point(10, (25 * count));
            label.Size = new Size(40, 20);
            label.Name = "label_" + (count + 1);
            label.Text = "label " + (count + 1);
            panel1.Controls.Add(label);

            TextBox textbox = new TextBox();
            count = panel1.Controls.OfType<TextBox>().ToList().Count;
            textbox.Location = new Point(60, 25 * count);
            textbox.Size = new Size(80, 20);
            textbox.Name = "textbox_" + (count + 1);
            textbox.TextChanged += new System.EventHandler(this.TextBox_Changed);
            panel1.Controls.Add(textbox);

            Button button = new Button();
            count = panel1.Controls.OfType<Button>().ToList().Count;
            button.Location = new Point(150, 25 * count);
            button.Size = new Size(60, 20);
            button.Name = "button_" + (count + 1);
            button.Text = "Button " + (count + 1);
            //button.Click += new System.EventHandler(this.Button1_Click);
            panel1.Controls.Add(button);

    }

1 个答案:

答案 0 :(得分:2)

首先,创建动态控件列表,然后向其中添加以编程方式创建的控件。然后,您可以一一删除控件。

    private List<Control> dynamicControls = new List<Control>();

    private void button1_Click_1(object sender, EventArgs e)
    {

        Label label = new Label();
        //...
        dynamicControls.Add(label);

        TextBox textbox = new TextBox();
        //...
        dynamicControls.Add(textbox);

        Button button = new Button();
        //...
        dynamicControls.Add(button);
    }

    public void RemoveDynamicControls()
    {
        if (dynamicControls.Count > 0)
        {
            var control = dynamicControls[0];

            if (panel1.Controls.Contains(control))
            {
                dynamicControls.Remove(control);
                panel1.Controls.Remove(control);
            }
        }
    }