這裡列舉出來了11個生命週期,一般的控制元件生命週期會經歷這11個生命週期,但是有一些特別的控制元件比如頁面控制元件System.Web.UI.Page等。
具體程式碼參考如下:
/// <summary> /// 1. 初始化 /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { OutPut("1. OnInit"); base.OnInit(e); this.Page.RegisterRequiresPostBack(this); } /// <summary> /// 2. 裝載檢視 /// </summary> /// <param name="savedState"></param> protected override void LoadViewState(object savedState) { OutPut("2. LoadViewState"); base.LoadViewState(savedState); } /// <summary> /// 3. 回傳資料處理 /// </summary> /// <param name="postDataKey"></param> /// <param name="postCollection"></param> /// <returns></returns> public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { OutPut("3. LoadPostData"); return true; } /// <summary> /// 4. 裝載時間 /// </summary> /// <param name="e"></param> protected override void OnLoad(EventArgs e) { OutPut("4. OnLoad"); base.OnLoad(e); } /// <summary> /// 5. 回傳事件通知 /// </summary> public virtual void RaisePostDataChangedEvent() { OutPut("5. RaisePostDataChangedEvent"); } /// <summary> /// 6. 處理回發事件 /// </summary> /// <param name="eventArgument"></param> public virtual void RaisePostBackEvent(string eventArgument) { OutPut("6. RaisePostBackEvent"); } /// <summary> /// 7. 預呈現 /// </summary> /// <param name="e"></param> protected override void OnPreRender(EventArgs e) { OutPut("7. OnPreRender"); base.OnPreRender(e); } /// <summary> /// 8 儲存檢視狀態 /// </summary> /// <returns></returns> protected override object SaveViewState() { OutPut("8. SaveViewState"); base.SaveViewState(); return new Pair(); } /// <summary> /// 9. 呈現 /// </summary> /// <param name="writer"></param> protected override void Render(HtmlTextWriter writer) { writer.Write("<input type='button' name=\"{0}\" value=\"Click Me!\" style='position: absolute; left: 20px; top: 280px;' onclick=\"{1}\" />", "[控制元件宣告週期]", Page.ClientScript.GetPostBackEventReference(this, "")); OutPut("9. Render"); base.Render(writer); } /// <summary> /// 10. 解除安裝 /// </summary> /// <param name="e"></param> protected override void OnUnload(EventArgs e) { OutPut("10. OnUnload"); base.OnUnload(e); } /// <summary> /// 11. 釋放資源 /// </summary> public override void Dispose() { OutPut("11. Dispose"); base.Dispose(); } private void OutPut(string strText) { if (this.DesignMode == false) { HttpContext.Current.Response.Write(strText + "<br />"); } } [Bindable(true)] [Category("Appearance")] [DefaultValue("")] [Localizable(true)] public string Text { get { String s = (String)ViewState["Text"]; return ((s == null) ? String.Empty : s); } set { ViewState["Text"] = value; } } protected override void RenderContents(HtmlTextWriter output) { output.Write(Text); }
這個程式碼複製到asp.net 伺服器控制元件中,即可除錯。