天天看點

簡單伺服器端控件 Simple Server Control

簡單伺服器端控件 Simple Server Control
簡單伺服器端控件 Simple Server Control

Code

namespace CustomTextBox

{

    [DefaultProperty("Text")]

    [ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]

    public class MyTextBox : WebControl,IPostBackDataHandler

    {

        [Bindable(true)]

        [Category("Appearance")]

        [DefaultValue("")]

        [Localizable(true)]

        public string Text

        {

            get

            {

                String s = (String)ViewState["Text"];

                return ((s == null) ? "[" + this.ID + "]" : s);

            }

            set

                ViewState["Text"] = value;

        }

        public MyTextBox()

            : base(HtmlTextWriterTag.Input)

            Text = "";

        protected override void AddAttributesToRender(HtmlTextWriter writer)

            writer.AddAttribute("type", "text");

            writer.AddAttribute("name", this.UniqueID);

            writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);

            writer.AddAttribute("ondblclick", Page.GetPostBackEventReference(this, string.Empty));

            base.AddAttributesToRender(writer);

        protected override void RenderContents(HtmlTextWriter writer)

            base.RenderContents(writer);

        // 傳回結果:

        //     如果伺服器控件的狀态由于回發而發生更改,則為 true;否則為 false。

        public bool LoadPostData(string postDataKey, NameValueCollection postCollection) {

            string postedVal = postCollection[postDataKey];

            string strText = Text;

            if (strText != postedVal)

                Text = postedVal;

                return true;

            return false;

        public event EventHandler TextChanged;

        protected virtual void OnTextChanged( EventArgs e)

            if (TextChanged != null)

                TextChanged(this, e);

        public void RaisePostDataChangedEvent() {

            OnTextChanged( new EventArgs());

    }

}