現象
GroupBoxなどのコンテナクラスにコントロールを追加するには以下のようにします。
this.groupBox1.Controls.Add(this.button1);
this.groupBox1.Controls.Add(this.checkBox1);
this.groupBox1.Controls.Add(this.label1);
コンテナからforeachなどでコントロールを取り出すには以下のようにします。
foreach (Control ctrl in this.groupBox1.Controls) {
...
}
感覚的には取り出す順序はAddした順になると考えますが、実際はそうならないことがあります。
対処方法
SetChildIndex()メソッドでコンテナ内のコントロールの順序を設定しておけば、設定した順序でコントロールを取り出すことが出来ます。
this.groupBox1.Controls.SetChildIndex(this.button1, 0);
this.groupBox1.Controls.SetChildIndex(this.checkBox1, 1);
this.groupBox1.Controls.SetChildIndex(this.label1, 2);