Page.RegisterRequiresControlState(Control) 方法

定義

將控制項註冊為,必須保存控制項狀態的控制項。Registers a control as one whose control state must be persisted.

public:
 void RegisterRequiresControlState(System::Web::UI::Control ^ control);
public void RegisterRequiresControlState (System.Web.UI.Control control);
member this.RegisterRequiresControlState : System.Web.UI.Control -> unit

參數

control
Control

要登錄的控制項。The control to register.

例外狀況

要註冊的控制項為 nullThe control to register is null.

RegisterRequiresControlState(Control) 方法只能在 PreRender 事件之前或發生期間呼叫。The RegisterRequiresControlState(Control) method can be called only before or during the PreRender event.

範例

下列程式碼範例顯示呼叫 RegisterRequiresControlState 方法的自訂伺服器控制項。The following code example shows a custom server control calling the RegisterRequiresControlState method.

public class Sample : Control {
    private int currentIndex = 0;
   
    protected override void OnInit(EventArgs e) {
        Page.RegisterRequiresControlState(this);
        base.OnInit(e);
    }

    protected override object SaveControlState() {
        return currentIndex != 0 ? (object)currentIndex : null;
    }

    protected override void LoadControlState(object state) {
        if (state != null) {
            currentIndex = (int)state;
        }
    }
}
Class Sample
  Inherits Control
  
  Dim currentIndex As Integer
  
      Protected Overrides Sub OnInit(ByVal e As EventArgs)
          Page.RegisterRequiresControlState(Me)
          currentIndex = 0
          MyBase.OnInit(e)
      End Sub
  
      Protected Overrides Function SaveControlState() As Object
          If currentIndex <> 0 Then
              Return CType(currentIndex, Object)
          Else
              Return Nothing
          End If
      End Function
  
      Protected Overrides Sub LoadControlState(ByVal state As Object)
          If (state <> Nothing) Then
              currentIndex = CType(state, Integer)
          End If
      End Sub
  
End Class

備註

使用控制項狀態的自訂伺服器控制項,必須在每個要求上呼叫 RegisterRequiresControlState 方法,因為在回傳事件期間,控制項狀態的註冊不會從要求傳遞至要求。Custom server controls that use control state must call the RegisterRequiresControlState method on each request because registration for control state is not carried over from request to request during a postback event. 建議您在 Init 事件中進行註冊。It is recommended that registration occur in the Init event.

適用於

另請參閱