سؤال

I am dynamically creating a list of CommandLink controls and adding them to a panel. I created a method to remove all of the CommandLink controls from the panel, and it's working for the most part, except it only seems to remove every other control. If I call the method again, it does the same thing with the remaining controls of only removing every other one. Can anyone tell me where I am going wrong here? Constructive criticism is also welcome.

    private void MainMenu_Load(object sender, EventArgs e)
    {
#if DEBUG
        // Generate dummy actions
        for (int i = 0; i < 20; i++)
        {
            CommandLink cl = AddCommandLink(String.Format("cl{0}",i), String.Format("Command #{0}", i), "The quick brown fox jumps over the lazy dog.", true);
            cl.Click += new EventHandler(CommandLinks_Click);
        }
#endif
    }

    private void CommandLinks_Click(object sender, EventArgs e)
    {
        ClearCommandLinks();
    }

    private CommandLink AddCommandLink( string name, string text, string note = "", bool shield = false )
    {
        int top = 0;
        foreach (Control c in splitMain.Panel2.Controls)
            if (c.GetType() == typeof(CommandLink))
                top = Math.Max(top, ((CommandLink)c).Bottom);
        CommandLink cl = new CommandLink();
        cl.Name = name;
        cl.Location = new Point(10, top + 10);
        cl.Width = splitMain.Panel2.ClientSize.Width - SystemInformation.VerticalScrollBarWidth - 20;
        cl.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
        cl.Text = text;
        if (!String.IsNullOrEmpty(note))
            cl.Note = note;
        if (shield)
            cl.Shield = true;
        splitMain.Panel2.Controls.Add(cl);
        return cl;
    }

    private void ClearCommandLinks()
    {
        foreach (Control c in splitMain.Panel2.Controls)
        {
            if (c.GetType() == typeof(CommandLink))
            {
                CommandLink cl = (CommandLink)c;
                splitMain.Panel2.Controls.Remove(cl);
            }
        }
    }
هل كانت مفيدة؟

المحلول

Try not removing from the list you are traversing.

do this:

List<Control> removeList = new List<Control>();
foreach (Control c in splitMain.Panel2.Controls)
{
   if (c.GetType() == typeof(CommandLink))
   {
      removeList.Add( c);
   }
}

foreach(Control c in removeList )
{
   splitMain.Panel2.Controls.Remove(c);
}

نصائح أخرى

I think altering the collection as you iterate it is the problem.

Try a for loop:

for (int index = 0; index < splitMain.Panel2.Controls.length...
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top