添加/删除具有相同引用名称的控件

当用户点击按钮时,我在一个接一个的面板上添加控件。 控件在面板上依次显示。 当面板已满(例如10)时,添加的下一个控件必须替换添加的第一个控件,但首先我需要删除第一个控件….问题是所有正在创建的控件都具有相同的引用例如“pic”,现在当我使用panel1.Controls.Remove(pic)它没有指定需要删除第一个位置的控件!!

int index = 0; if (util.GetSize() != 10) { ms.Controls.Add(musNote); } else { ms.Controls.Add(musNote); //this to replace first musNote added... but before I need to remove the musNote that in that position already (problem all of the are musNote!! index++; if (index == 10) { index = 0; } } musNote.ShowNote(); 

以上不是整个代码,但应足以解决问题..如果有任何信息。 需要请问我。 请提前帮忙。

如果您只想删除第一个孩子,请使用RemoveAt方法

 myPanel.Controls.RemoveAt(0); 

不要使用上面的代码,它会在Handle泄漏,使用Dispose作为评论中建议的@Hans

 myPanel.Controls[0].Dispose();//This takes care of destroying the window