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 或数组 及其他的基本数据类型,及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;
}
}
