ASP.NET自定义Web服务器控件之Button控件
本文实例讲述了ASP.NET自定义Web服务器控件之Button控件实现方法。分享给大家供大家参考。具体实现方法如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Linq; usingSystem.Text; usingSystem.Web; usingSystem.Web.UI; usingSystem.Web.UI.WebControls; //自定义web服务器button namespaceMyControls { [DefaultProperty("Text")] [ToolboxData("<{0}:MyButtonrunat=server></{0}:MyButton>")] publicclassMyButton:WebControl,IPostBackEventHandler { [Bindable(true)] [Category("Appearance")] [DefaultValue("")] [Localizable(true)] publicstringText { get { Strings=(String)ViewState["Text"]; return((s==null)?String.Empty:s); } set { ViewState["Text"]=value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]//生成属性时,按属性内部内容生成(例如在此控件里面(Size-Height,Size_Width)) //[PersistenceMode(PersistenceMode.InnerProperty)]//以子标签的形式显示(例如<SizeWidth=""Height=""/>) publicSizeSize { get { if(ViewState["Size"]==null){ ViewState["Size"]=newSize(); } return(Size)ViewState["Size"]; } set { ViewState["Size"]=value; } } //定义控件的标签形式 protectedoverrideHtmlTextWriterTagTagKey { get { returnHtmlTextWriterTag.Input; } } //初始化 protectedoverridevoidOnInit(EventArgse) { this.Style.Add("width",Size.Width+"px"); this.Style.Add("height",Size.Height+"px"); this.Attributes.Add("type","submit");//提交按钮 this.Attributes.Add("value",Text); this.Attributes.Add("name",this.UniqueID);//回发事件必须有的一个属性 base.OnInit(e); } //打印当前控件的内容 protectedoverridevoidRenderContents(HtmlTextWriteroutput) { //output.Write(Text); } publicdelegatevoidClickHandle(); privateobjectkey=newobject(); publiceventClickHandleClick{ add{ this.Events.AddHandler(key,value); } remove{ this.Events.RemoveHandler(key,value); } } //按钮的回发事件 publicvoidRaisePostBackEvent(stringeventArgument) { ClickHandlehandle=(ClickHandle)base.Events[key]; if(handle!=null){ handle(); } } } }
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%> <%@Registerassembly="MyControls"namespace="MyControls"tagprefix="cc1"%> <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server"> <title></title> </head> <body> <formid="form1"runat="server"> <div> <!--自定义服务器按钮控件--> <cc1:MyButtonID="MyButton1"Size-Height="30"Size-Width="290"OnClick="btnSubmit"Text="我是一个单独的提交按钮(自定义服务器)"runat="server"/> </div> </form> </body> </html>
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Web; usingSystem.Web.UI; usingSystem.Web.UI.WebControls; publicpartialclass_Default:System.Web.UI.Page { protectedvoidPage_Load(objectsender,EventArgse) { } //自定义服务器控件 protectedvoidbtnSubmit(){ Response.Write("我是自定义服务器控件的点击事件"); } }
希望本文所述对大家的asp.net程序设计有所帮助。