操作說明:在執行階段時從控制項集合新增或移除
常見的應用程式開發工作為新增和移除您表單上任何容器控制中的控制項 (例如 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(); } }