Control.ControlCollection.Clear Method


从集合中移除所有控件。Removes all controls from the collection.

 virtual void Clear();
public virtual void Clear ();
abstract member Clear : unit -> unit
override this.Clear : unit -> unit
Public Overridable Sub Clear ()



下面的代码示例移除 Panel派生类的 Control.ControlCollection 中的所有 Control 对象。The following code example removes all the Control objects in the Control.ControlCollection of the derived class Panel. 该示例要求您已在 Form上创建了一个 Panel、一个 Button和至少一个其他控件。The example requires that you have created a Panel, a Button, and at least one other control on a Form. 其他控件添加到 Panel 控件中,并且 Panel 添加到 Form中。The other controls are added to the Panel control, and the Panel added to the Form. 单击该按钮时,面板中包含的所有控件都将从 Control.ControlCollection中移除。When the button is clicked, all the controls contained in the panel are removed from the Control.ControlCollection.

   // Clear all the controls in the Panel.
   void clearButton_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
// Clear all the controls in the Panel.
private void clearButton_Click(object sender, System.EventArgs e)
' Clear all the controls in the Panel.
Private Sub ClearButton_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles ClearButton.Click
End Sub


您可以使用 Clear 方法从父控件中删除整个控件集合。You can use the Clear method to remove the entire collection of controls from a parent control.

若要从集合中移除单个控件,请使用 RemoveRemoveAt 方法。To remove an individual control from the collection, use the Remove or RemoveAt methods.


调用 Clear 方法不会从内存中删除控件句柄。Calling the Clear method does not remove control handles from memory. 必须显式调用 Dispose 方法,以避免内存泄漏。You must explicitly call the Dispose method to avoid memory leaks.

若要向集合添加新的 Control 对象,请使用 AddAddRange 方法。To add new Control objects to the collection, use the Add or AddRange methods.

Notes to Inheritors

当在派生类中重写 Clear() 时,请确保调用基类的 Clear() 方法,以确保从集合中移除所有控件。When overriding Clear() in a derived class, be sure to call the base class's Clear() method to ensure that all the controls are removed from the collection.

Applies to