我正在动态创建CommandLink
controls列表并将其添加到面板中。我创建了一个从面板中删除所有CommandLink
控件的方法,它在大多数情况下都有效,除了它似乎只删除所有其他控件。如果我再次调用该方法,它会对剩余的控件执行相同的操作,只删除其他每个控件。谁能告诉我这里哪里出错?建设性的批评也是受欢迎的。
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);
}
}
}
答案 0 :(得分:3)
请勿尝试从正在浏览的列表中删除。
这样做:
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);
}
答案 1 :(得分:0)
我认为在迭代它时改变集合是个问题。
尝试for循环:
for (int index = 0; index < splitMain.Panel2.Controls.length...