アプリケーション開発の一般的なタスクは、フォーム上の任意のコンテナー コントロール ( Panel 、 GroupBox コントロール、フォーム自体など) にコントロールを追加したり、コントロールを削除したりすることです。 デザイン時に、コントロールをパネルまたはグループ ボックスに直接ドラッグできます。 実行時に、これらのコントロールは Controls
コレクションを維持し、コントロールに配置されているコントロールを追跡します。
注
次のコード例は、コントロール内のコントロールのコレクションを保持するすべてのコントロールに適用されます。
プログラムによってコレクションにコントロールを追加するには
追加するコントロールのインスタンスを作成します。
新しいコントロールのプロパティを設定します。
親コントロールの
Controls
コレクションにコントロールを追加します。次のコード例は、 Button コントロールのインスタンスを作成する方法を示しています。 Panel コントロールを持つフォームと、作成されるボタンのイベント処理メソッド (
NewPanelButton_Click
) が既に存在する必要があります。Public NewPanelButton As New Button() Public Sub AddNewControl() ' The Add method will accept as a parameter any object that derives ' from the Control class. In this case, it is a Button control. Panel1.Controls.Add(NewPanelButton) ' The event handler indicated for the Click event in the code ' below is used as an example. Substite the appropriate event ' handler for your application. AddHandler NewPanelButton.Click, AddressOf NewPanelButton_Click End Sub
public Button newPanelButton = new Button(); public void addNewControl() { // The Add method will accept as a parameter any object that derives // from the Control class. In this case, it is a Button control. panel1.Controls.Add(newPanelButton); // The event handler indicated for the Click event in the code // below is used as an example. Substitute the appropriate event // handler for your application. this.newPanelButton.Click += new System.EventHandler(this. NewPanelButton_Click); }
プログラムによってコレクションからコントロールを削除するには
イベントからイベント ハンドラーを削除します。 Visual Basic では、 RemoveHandler ステートメント キーワードを使用します。C# では、 -= 演算子を使用します。
Remove
メソッドを使用して、パネルのControls
コレクションから目的のコントロールを削除します。Dispose メソッドを呼び出して、コントロールによって使用されるすべてのリソースを解放します。
Public Sub RemoveControl() ' NOTE: The code below uses the instance of ' the button (NewPanelButton) from the previous example. If Panel1.Controls.Contains(NewPanelButton) Then RemoveHandler NewPanelButton.Click, AddressOf _ NewPanelButton_Click Panel1.Controls.Remove(NewPanelButton) NewPanelButton.Dispose() End If End Sub
private void removeControl(object sender, System.EventArgs e) { // NOTE: The code below uses the instance of // the button (newPanelButton) from the previous example. if(panel1.Controls.Contains(newPanelButton)) { this.newPanelButton.Click -= new System.EventHandler(this. NewPanelButton_Click); panel1.Controls.Remove(newPanelButton); newPanelButton.Dispose(); } }
こちらも参照ください
.NET Desktop feedback