Search code examples
c#panel

Delete all dynamically created panels in a panel


I have a contact management application (which you helped me a lot to do :D) and on my main form I have a panel called panel_contact. Inside there are panels containing the contacts that are displayed:

enter image description here

But here's my problem: When I create a contact, the contact_panel reloads to add the one I just created. For example, in the picture below I added Jackie and you can see that the first contact has duplicated itself, and that's not what I want.

enter image description here

So how do I delete all the panels in my contact_panel? I've already tried it:

panel_contact.Controls.Clear(); //Don't work
panel1.Invalidate(); //Don't work

Anyone have a solution, please? Thank you.

EDIT : COMPLETE CODE :

namespace Contact
{
    public partial class Contact : Form
    {

        List<Personne> contacts = new List<Personne>(); //Contient tous les contacts

        public Contact()
        {
            this.Icon = AppResources.icon;
            InitializeComponent();
        }


        private void Picture_add_Click(object sender, EventArgs e)
        {
            //Ouvre la fenêtre de création de contact
            //Add.cs
            Add ajouterWindow = new Add();
            ajouterWindow.ShowDialog();

            this.Contact_Load(this, null);
        }

        private void Contact_Load(object sender, EventArgs e)
        {
            //Création des class contact depuis le fichier txt

            string path = System.IO.Path.GetFullPath(@"contact.txt");

            try
            {
                List<string> contactsBrut = File.ReadAllLines(path).ToList();

                string[] inforamtions = new string[15];
                string[] notes = new string[8];

                for (int i = 0; i < contactsBrut.Count; i++)
                {
                    inforamtions = contactsBrut[i].Split('#');

                    for (int z = 0; z < inforamtions.Length; z++) //remplace les valeurs incorrect par null
                    {
                        if (String.IsNullOrWhiteSpace(inforamtions[z]) || String.IsNullOrEmpty(inforamtions[z]))
                        {
                            inforamtions[z] = null;
                        }
                    }

                    int age = Convert.ToInt32(inforamtions[2]);
                    bool isMan = false;

                    if (inforamtions[4] == "True") {
                        isMan = true;
                    }
                    else {
                        isMan = false;
                    }

                    contacts.Add(new Personne(inforamtions[0], inforamtions[1], age, inforamtions[3], isMan,
                       inforamtions[5], inforamtions[6], inforamtions[7], inforamtions[8], inforamtions[9], inforamtions[10], inforamtions[11],
                       inforamtions[12], inforamtions[13], inforamtions[14], inforamtions[15]));
                }

            }
            catch
            {
                MessageBox.Show("Erreur avec les données de l'application"); 
            }

            //Afficher les contacts
            if(contacts.Count == 0)
            {
                label_aucunContact.Show();
            }
            else
            {
                label_aucunContact.Hide();

                ClearPanel();
                afficherContact();

            }
            //Continuation du load
        }

        private void afficherContact()
        {
            int x = 4;
            int y = 4;
            for (int i = 0; i < contacts.Count; i++)
            {
                var control = new PersonControl(contacts[i]);
                control.Location = new Point(x, y);
                panel_contact.Controls.Add(control);
                y += control.Height + 2;
            }
        }

        private void Picture_add_MouseHover(object sender, EventArgs e)
        {
            ToolTip tt = new ToolTip();
            tt.SetToolTip(this.picture_add, "Ajouter un contact");
        }

        private void ClearPanel()
        {
            foreach (var control in panel_contact.Controls.OfType<PersonControl>().ToList())
                panel_contact.Controls.Remove(control);
        }

    }
}

Here is the link to the project : https://www.mediafire.com/file/sb06mnajgm57vn1/Contact.rar/file


Solution

  • Assuming we continue your project with the user control solution, you can write:

    using System.Linq;
    
    private void ClearPersonControls(Panel panel)
    {
      foreach ( var control in panel.Controls.OfType<PersonControl>().ToList() )
        panel.Controls.Remove(control);
    }
    

    It gets all controls in the panel that are type of PersonControl.

    We need to create a List of the result to avoid collision of references when removing.

    Next we do a loop on it and ask the panel to delete each controls.

    Usage:

    private void UpdatePanel(Panel panel)
    {
      ClearPersonControls(panel);
      CreatePersonControls(panel);
    }
    

    Where CreatePersonControls is a method containing the code of the previous question to create the display with some PersonControl

    You can of course put all the code in the UpdatePanel method at same time, if not many lines, without creating Clear and Create. Do how what you feel.

    If you need, you can add a refresh, but after seeing your code it is not necessary:

    panel.Refresh();