本文共 1632 字,大约阅读时间需要 5 分钟。
在Visual studio 2015中可以通过Add-->New Item,添加Web Forms Server Control,自动生成的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication23 { [DefaultProperty( "Text" )] [ToolboxData( "<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>" )] public class WebCustomControl1 : WebControl { [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; } } protected override void RenderContents(HtmlTextWriter output) { output.Write(Text); } } } |
在Web Page(即在aspx文件)中引用该Server Control,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <%@ Page Language= "C#" AutoEventWireup= "true" CodeBehind= "WebForm1.aspx.cs" Inherits= "WebApplication23.WebForm1" %> <%@ Register Assembly= "WebApplication23" Namespace= "WebApplication23" TagPrefix= "ccl" %> <!DOCTYPE html> <html xmlns= "http://www.w3.org/1999/xhtml" > <head runat= "server" > <title></title> </head> <body> <form id= "form1" runat= "server" > <div> <ccl:WebCustomControl1 ID= "ServerControl1" runat= "server" Text= "daniel_test" /> </div> </form> </body> </html> |
在使用Register引用该Server Control后,在ToolBox中就会出现该自定义的服务器控件,如图:
参考链接: