Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove panels from button C#

I have created a function that creates a new panel each time a button is pressed, alongside with a button, which should remove the entire panel when pressed.

Here is my code for creating the panels and the button :

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);
        }

Considering that every panel created has this delbutton , how can i remove the panel of which delbutton button was pressed?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to add this method to the button, but it removes panel randomly :

void ButtonFunction_Click (Object sender,EventArgs e)
        {

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

>Solution :

You can add the relevant Panel as a Tag property of its Button, then you can get that in the Click handler

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;
    flowLayoutPanel1.Controls.Remove(button);
    flowLayoutPanel1.Controls.Remove((Control)button.Tag);
    button.Dispose();
    ((Control)button.Tag).Dispose();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading