日期:2011-09-19 浏览次数:20470 次
(一). 概述
示例制作一个与Asp.net TextBox同样功能的 TextBox control, 可以了解一下
Control底层的实现原理
(二). 代码实现
1. 核心控件生成代码文件TextBox.cs
1 1using System;
2 2using System.Data;
3 3using System.Configuration;
4 4using System.Web;
5 5using System.Web.Security;
6 6using System.Web.UI;
7 7using System.Web.UI.WebControls;
8 8using System.Web.UI.WebControls.WebParts;
9 9using System.Web.UI.HtmlControls;
10 10
11 11using System.Text;
12 12using System.Collections.Specialized;
13 13
14 14namespace KingControls
15 15{
16 16 /**//// <summary>
17 17 /// Making a TextBox WebControl
18 18 /// </summary>
19 19 public class TextBox : Control, IPostBackDataHandler //IPostBackDataHandler: 处理回发数据使用
20 20 {
21 21 public TextBox()
22 22 {
23 23 }
24 24
25 25 /**//// <summary>
26 26 /// 设置或获取显示文本
27 27 /// </summary>
28 28 public string Text
29 29 {
30 30 //Web编程中要用ViewState为两次回发共享数据
31 31 get
32 32 {
33 33 String s = (String)ViewState["Text"];
34 34 return ((s == null) ? String.Empty : s);
35 35 }
36 36
37 37 set
38 38 {
39 39 ViewState["Text"] = value;
40 40 }
41 41 }
42 42
43 43 /**//// <summary>
44 44 /// 生成呈现Html格式标记
45 45 /// </summary>
46 46 /// <param name="writer"></param>
47 47 protected override void Render(HtmlTextWriter writer)
48 48 {
49 49 StringBuilder sb = new StringBuilder();
50 50 sb.Append("<input type=\"text\" name=");
51 51 sb.Append("\"" + UniqueID + "\""); //标识符,继承自基类Control
52 52 sb.Append("value=");
53 53
54 54 //HttpUtility.HtmlEncode 将用户输入字串转换成Html格式,主要转义用户输入的html关键字为非html关键字字符
55 55 sb.Append("\"" + HttpUtility.Html