foreach在C#中按降序控制

时间:2013-12-22 22:29:52

标签: c# foreach controls

我有一段FOREACH代码,它是音乐笔记的一部分

foreach (MusicNote mn in pictureBox1.Controls)
{
    sp.SoundLocation = @"..\\..\\bin\\Debug\\sound\\mapped\\" + mn.pitch+ ".wav"; //find that pressed note
    Thread.Sleep(mn.duration * 100); //The Ticks * 100 to convert them into milliseconds
    sp.Play(); //play it
}

这应该遍历所有控件并逐个播放,但问题是它从最后一个添加而不是第一个开始,就像我希望它意味着它在降序中播放订单不是升序就像我希望的那样。知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

Controls属性中控件的顺序基于每个控件的z-index(因为Controls属性返回ControlCollection,而不仅仅是正常列表)。

您可以使用SetChildIndex方法控制每个控件的z-index。如果在添加控件时使用此方法显式控制z-index(您没有说控件是如何添加的,所以我假设您是在代码中手动执行),它们应该按照您想要的顺序出现你遍历Controls属性。

答案 1 :(得分:0)

pictureBox1.Controls.Cast<Control>().Reverse()