Recently wanted to write a blog record of yourself learning to develop server controls.
The first step: Build the environment.
1. Create a new project class library for saving the control;
2. Create a new Web project to invoke the control;
Step two: Under the Control class library, create a new server control class TextBox.cs file. The code is as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Linq;usingSystem.Text;usingsystem.web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;namespacejhsoft.ui.web.controls{[Defaultproperty ("Text")] [ToolBoxData ("<{0}:textbox runat=server></{0}:textbox>")] Public classTextbox:webcontrol {[Bindable (true)] [Category ("appearance")] [DefaultValue ("")] [Localizable (true)] Public stringText {Get{String s= (String) viewstate["Text"]; return(s = =NULL) ?string.empty:s); } Set{viewstate["Text"] =value; } } protected Override voidrendercontents (HtmlTextWriter output) {output. Write (Text); } }}
Modification method: RenderContents
protected Override void rendercontents (HtmlTextWriter output) { output. Write ("<input type= ' text ' value= '" "'/>" ); }
Step Three:
1. Reference the Control class library.
2. Registering the control prefix in Webconfig
3. In the Web project, create a new page textbox.aspx, call the new server control <c:TextBox>
<%@ Page language="C #"autoeventwireup="true"Codebehind="TextBox.aspx.cs"inherits="JHSoft.SYS.Web.TextBox"%><! DOCTYPE html>"http://www.w3.org/1999/xhtml">"Server"> <meta http-equiv="Content-type"Content="text/html; Charset=utf-8"/> <title></title>"Form1"runat="Server"> <c:textbox runat="Server"text="Test"></c:TextBox> </form></body>It should be stated that:
The control here <c:textbox runat= "Server" text= "Test" ></C:TEXTBOX> after execution completes, the generated HTML code is:
In the TextBox.cs class
protected override void RenderContents (HtmlTextWriter output)
{
Output. Write ("<input type= ' text ' value= '" + text + "'/>"); Generated normal control, text is the displayed value
}
ASP. NET server Control development series one