1

我在窗口窗体的面板上动态生成了控件,我还生成了一个用于删除控件的按钮,控件在一行代码是,

    int c = 0;
    private void button1_Click(object sender, EventArgs e)
    {
        int v;
        v = c++;
        panel1.VerticalScroll.Value = VerticalScroll.Minimum;
        ComboBox combo = new ComboBox();
        combo.Name = "combobox" + v ;
        combo.Location = new Point(30, 5 + (30 * v));

        ComboBox combo2 = new ComboBox();
        combo2.Name = "combobox2" + v ;
        combo2.Location = new Point(170, 5 + (30 * v));

        TextBox txt = new TextBox();
        txt.Name = "txtbx" + v;
        txt.Location = new Point(300, 5 + (30 * v));

        TextBox txt2 = new TextBox();
        txt2.Name = "txtbx2" + v;
        txt2.Location = new Point(450, 5 + (30 * v));

        TextBox txt3 = new TextBox();
        txt3.Name = "txtbx3" + v;
        txt3.Location = new Point(600, 5 + (30 * v));

        Button btn = new Button();
        btn.Name = "btn" + v;
        btn.Text = "Remove";
        btn.Location = new Point(750, 5 + (30 * v));



        panel1.Controls.Add(combo);
        panel1.Controls.Add(btn);
        panel1.Controls.Add(txt);
        panel1.Controls.Add(combo2);
        panel1.Controls.Add(txt2);
        panel1.Controls.Add(txt3);
        btn.Click += new EventHandler(btn_Click);

    }
    private void btn_Click(object sender, EventArgs e)
    {

        // what i have to write here for removing only the textbox and combobox and  button itself to be removed only the controls which are  aside the button

    }

我必须在按钮单击事件中写什么,以便仅删除文本框和组合框以及要删除的按钮本身 按钮旁边的控件其他行控件不应受此影响,

4

2 回答 2

2
foreach(var item in panel1.Controls)
{

    if(item is TextBox || item is ComboBox)
    {
          panel1.Controls.Remove(item);
    }


}

或者你也可以在下面试试这个。

 var list = (from object item in panel1.Controls where item is TextBox || item is ComboBox select item as Control).ToList();

            list.ForEach(x => panel1.Controls.Remove(x));
于 2012-12-14T15:31:37.890 回答
1

您需要在包含的元素中按名称查找控件。

这取决于您开发的框架。C# 不是很有帮助;)

然后你可以删除它

SomeParentElement.Comtrols.Remove(SomeElement)
于 2012-12-14T15:34:07.347 回答