LoginSignup
6
4

More than 5 years have passed since last update.

コンテナに格納したコントロールを取り出す順序

Posted at

現象

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);
6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4