日期:2010-10-12 浏览次数:20581 次
为自定义服务器控件实现事件,是一个比较复杂的过程。开发人员不仅需要根据上一篇文章中介绍的方法,实现捕获回传事件,而且有时候还需要参与回传数据处理过程。本文将通过典型应用介绍处理回传数据的方法。
1. 实现处理回传数据
在上一篇文章介绍的捕获回传事件过程中,往往都不涉及回传到服务器的控件数据。开发人员主要实现IPostBackEventHandler接口就能够成功捕获事件,并为之定义事件处理程序。然而,有些服务器控件在应用过程中,涉及回传数据的变化等情况。例如,自定义控件是一个输入控件,当用户输入并回传后,可能会由于回传数据的变化而引发一些事件。为了处理以上问题,控件类必须实现IPostBackDataHandler接口。下面列举了接口声明代码。
public interface IPostBackDataHandler{ public bool LoadPostData ( string postDataKey, NameValueCollection postCollection ); public void RaisePostDataChangedEvent ();} |
public virtual bool LoadPostData(string postDataKey,NameValueCollection postData) { string presentValue = Text; //旧数据 string postedValue = postData[postDataKey];//新数据 //检查新旧数据 if(presentValue.Equals(postedValue) || presentValue == null) { Text = postedValue; return true; } return false; } |
public virtual void RaisePostDataChangedEvent() { OnTextChanged(EventArgs.Empty); } |
2. 典型应用
下面通过一个典型实例说明处理回传数据的核心过程。创建一个自定义文本框控件WebCustomControl,其文本属性Text因回传而更改。控件在加载回传数据后引发TextChanged事件。控件类源代码如下所示:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebControlLibrary{ [DefaultProperty("Text")] [ToolboxData("<{0}:WebCustomControl runat=server></{0}:WebCustomControl>")] public class WebCustomControl : WebControl, IPostBackDataHandler { // 实现Text属性 [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; } } //重写控件呈现方法RenderContents protected override void RenderContents(HtmlTextWriter output) { output.AddAttribute(HtmlTextWriterAttribute.Type, "text"); output.AddAttribute(HtmlTextWriterAttribute.Value, Text); output.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); output.RenderBeginTag(HtmlTextWriterTag.Input); output.RenderEndTag();
免责声明: 本文仅代表作者个人观点,与爱易网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
|