【C#】フォームをまとめて操作する方法

スポンサーリンク

フォームをまとめて操作するにはフォームをList化する

buttonやtextBoxなどのフォームをまとめて操作したいという場面がでてくることがあります。そういうときは、buttonやtextBoxなどのフォームをList化します。buttonやtextBoxはListの型にあてることができます。

おそらくpublicなListで使うことがおおいとおもわれますのでpublicでの書き方をかきます。

public List<Button> buttonList = new List<Button>{this.button1, this.button2, this.button3};

これで3つのボタンをまとめて操作することができます。

次にList化したボタンを1つ1つの要素として取り出します。Listから要素を取り出すには foreach構文 を使います。例えば、ボタンを操作不可能にしたい場合はbutton.Enabled = falseですので

foreach(var bl in this.buttonList){
bl.Enabled = false;
}

これで3つのボタンをまとめて操作不可能にできます。

よくつかう構文だと思いますのでメソッド化しておくことをおすすめします。

public void ButtonTrue(){
foreach(var bl in this.buttonList){
bl.Enabled = true;
}
}

public void ButtonFalse(){
foreach(var bl in this.buttonList){
bl.Enabled = false;
}
}

publicなメソッドですのでthis.メソッドで呼び出せるかと思います。

this.ButtonFalse();
this.ButtonTrue();

コメント

タイトルとURLをコピーしました