在WEB自訂控制項中實現事件及自動儲存值

來源:互聯網
上載者:User

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Collections.Specialized;
namespace MyWebControls
{
 /// <summary>
 /// 建立一個派生於WEBCONTROL的類
 /// 實現一個公有建構函式,它將調用基類建構函式來指定伺服器控制項應該輸出一個input元素
 /// 重寫AddAttributesToRender方法,調用該方法是為了允許衍生類別為根項目input 添加屬性
 /// 我們將添加一個name屬性,它的值由uniqueID特性派生,asp.net使用這個特性來儲存每個控制項的唯一ID。
 /// </summary>
 [DefaultProperty("Text"),
  ToolboxData("<{0}:MyTextBox runat=server></{0}:MyTextBox>")]
 public class MyTextBox : System.Web.UI.WebControls.WebControl,IPostBackDataHandler
 {
  public MyTextBox():base("input")
  {
  }

  //使用ViewState對象將值儲存起來,此對象的有效範圍為當前頁面都可以存取.最終儲存在用戶端。每次都會進行回送
  //ViewState是StateBag類,可存放的資料類型有 int bool string 或數組 及其他的基礎資料型別 (Elementary Data Type),及arraylist,hashtable,
  //或具有類型轉換器的類型,可以串列的類型
  public string Text
  {
   get
   {
    if(ViewState["value"]==null)
    {
     return String.Empty;
    }
    return (string)ViewState["value"];
   }
   set
   {
    ViewState["value"]=value;
   }
  }

  protected override void AddAttributesToRender(HtmlTextWriter writer)
  {
   base.AddAttributesToRender (writer);
   writer.AddAttribute(HtmlTextWriterAttribute.Name,UniqueID);
   writer.AddAttribute("type","text");
   if(Text!=null)
    writer.AddAttribute("value",Text);
  }

  #region IPostBackDataHandler 成員

  //為了訪問回送資料,伺服器控制項要實現IPostBackDataHandler介面,有二個方法
  public void RaisePostDataChangedEvent()
  {
   //如果使用者回送的資料發生改變則,發生事件
   if(OnMyTextChnaged!=null)
   {
    OnMyTextChnaged(this,EventArgs.Empty);
   }
  }

  //當有回送發生並且某個控制項有回送資料時,此方法就會被調用,該方法為頁面上所有需要訪問回送資料的控制項依次調用。
  //此方法如果返回真,那麼在為頁面上所有其他帶有回送資料的控制項調用過LoadPostData方法後,RaisePostDataChangedMethod將被調用。
  //如果返回假,則不調用.由於在此方法裡引發事件會引起不可預知的結果,所以一定要在RaisePostDataChangedEvent裡引發事件。
  //
  public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
  {
   bool raiseEvent=false; //要不要觸發事件的標誌
   //如果上一次的文本與回送的文本不一樣
   if(Text!=postCollection[postDataKey])
   {
    raiseEvent=true;
    Text=postCollection[postDataKey];//將回送的值儲存
   }
   return raiseEvent;
  }

  #endregion

  //註冊一個事件,文本改變事件
  public event EventHandler OnMyTextChnaged;

 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.