語言

ControlCollection.Clear 方法

定義

移除目前伺服器控制 ControlCollection 物件中的所有控制項。

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

範例

以下程式碼範例示範覆寫該 Control.CreateChildControls 方法,並利用該 Clear 方法刪除物件中先前所有 ControlCollection 的子控制項。 在這種情況下,你必須這麼做,避免你控制 ControlCollection 中的過時物件被不當顯示。

// Override to create repeated items.
protected override void CreateChildControls() {
    object o = ViewState["NumItems"];
    if (o != null) {
       // Clear any existing child controls.
       Controls.Clear();

       int numItems = (int)o;
       for (int i=0; i < numItems; i++) {
          // Create an item.
          RepeaterItem item = new RepeaterItem(i, null);
          // Initialize the item from the template.
          ItemTemplate.InstantiateIn(item);
          // Add the item to the ControlCollection.
          Controls.Add(item);
       }
    }
}
' Override to create repeated items.
Protected Overrides Sub CreateChildControls()
    Dim O As Object = ViewState("NumItems")
    If Not (O Is Nothing)
       ' Clear any existing child controls.
       Controls.Clear()

       Dim I As Integer
       Dim NumItems As Integer = CInt(O)
       For I = 0 To NumItems - 1
          ' Create an item.
          Dim Item As RepeaterItemVB = New RepeaterItemVB(I, Nothing)
          ' Initialize the item from the template.
          ItemTemplate.InstantiateIn(Item)
          ' Add the item to the ControlCollection.
          Controls.Add(Item)
       Next
    End If
End Sub

備註

當你覆寫 ControlCollection and Control.CreateChildControls 方法時,可以用這個方法清空自訂控制項DataBind。 當你開發複合式、模板化控制項或模板化資料綁定控制項時,請這麼做。

適用於

另請參閱