0

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

braX
  • 11,506
  • 5
  • 20
  • 33

1 Answers1

1

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();
  • Mhh it doesn't work and yes, it's about this project. Maybe I'm misplacing it? I measure it just before the for loop that adds the userControl dynamically :'( – Rayane Staszewski Nov 03 '19 at 09:59
  • It's the same code, but with a function it still doesn't work. – Rayane Staszewski Nov 03 '19 at 10:06
  • Strange, can you post some code or a zip with your project folder, please? –  Nov 03 '19 at 10:07
  • It's okay! It's okay! I changed the location of the code now all works fine Thank you very much! – Rayane Staszewski Nov 03 '19 at 10:09
  • No, I'm sorry, it still doesn't work. I'll add my complete code – Rayane Staszewski Nov 03 '19 at 10:19
  • Can you create a link to a zip containing the project folder as well as a `contact.txt`, please? (You should put the `this.Icon = AppResources.icon;`after `InitializeComponents()` in the constructor) –  Nov 03 '19 at 10:28
  • 1
    Ok, the problem is not with ClearPanel and CreatePanel: the problem is that when you add a new contact you reload the list so the duplicates. To solve that, add `contacts.Clear();` at the beginning of `Contact_Load`. You can also in fact move the `ClearPanel` at the beginning of `afficherContact`. The code in my answer if to have a `UpdatePanel` that call `Clear` and `Create`. But since methods are small you can put the code in only one method at same time. Answer updated. –  Nov 03 '19 at 10:47