如何从按钮 C# 中删除面板

How to remove panels from button C#

我创建了一个函数,每次按下按钮时都会创建一个新面板,旁边还有一个按钮,按下时应该会删除整个面板。

这是我创建面板和按钮的代码:

Panel panel;
        private void button1_Click(object sender, EventArgs e)
        { 
            panel = new Panel();
            panel.BackColor = Color.FromArgb(38, 38, 38);
            panel.Margin = new System.Windows.Forms.Padding(10);
            flowLayoutPanel1.Controls.Add(panel);
            panel.Show();
            
            Button delbutton = new Button();
            delbutton.Text = "X";
            flowLayoutPanel1.Controls.Add(delbutton);

            delbutton.Click += new EventHandler(this.ButtonFunction_Click);
        }

考虑到创建的每个面板都有这个 delbutton ,我怎样才能删除按下 delbutton 按钮的面板?

我尝试将此方法添加到按钮,但它随机删除了面板:

void ButtonFunction_Click (Object sender,EventArgs e)
        {

            foreach (Control controlObj in flowLayoutPanel1.Controls)
            {
                flowLayoutPanel1.Controls.Remove(controlObj);
                controlObj.Dispose();
            }
        }

您可以添加相关 Panel 作为其 ButtonTag 属性,然后您可以在 Click 处理程序

private void button1_Click(object sender, EventArgs e)
{ 
    var panel = new Panel
    {
        BackColor = Color.FromArgb(38, 38, 38),
        Margin = new Padding(10),
    };
    flowLayoutPanel1.Controls.Add(panel);
    panel.Show();
            
    var delbutton = new Button
    {
        Text = "X",
        Tag = panel,
    };
    delbutton.Click += ButtonFunction_Click;
    flowLayoutPanel1.Controls.Add(delbutton);
}

private void ButtonFunction_Click(Object sender, EventArgs e)
{
    var button = (Button)sender;
    ((Control)button.Tag).Dispose();
    button.Dispose();
}