Welcome 微信登录

首页 / 网页编程 / ASP.NET / ASP.NET服务器控件编程之热身运动

ASP.NET服务器控件编程之热身运动2011-02-21创建Asp.net里的服务器控件和Windows Form的控件一样,也有几种方式:

1、用户控件(user control)

2、从Control、WebControl派生的自定义控件

3、从已有的Asp.net服务器控件扩展

用户控件以.ascx为扩展名,并保存为文本文件,用户控件不像从Control和WebControl派生下来的服务器控件那样需要预编译,当用户控件在.aspx页面中使用的时候,页面解析器从.aspx文件中动态地生成一个类,并且将其编译到一个装配件中。其优点有:解决了代码复用,同时每一个用户控件有自己的对象模型,其编写语言和.aspx页面的语言无关。

从已有的Asp.net服务器控件扩展,主要是对.net原生的服务器控件的功能加强以适用我们开发和最终用户的需要。

从Control、WebControl派生的自定义控件以编译过的类库形式部署的。

上述的1和3在本系列中将不做讲解,在本系列中只讲解从Control、WebControl派生的服务器控件。

我们要编写一个自定义控件,只要从Control、WebControl继承即可,Control已经实现了IComponent接口,而WebControl本身又是从Control上派生下来的,因而他们也支持组件的可视化设计。

Render方法和HtmlTextWriter类,当我们从一个Control类派生一个Asp.net服务器控件时,Control类为我们提供了可重载的Render和一个HtmlTextWriter类型的实例,Render方法就是将服务器控件内容发送到提供的 HtmlTextWriter 对象,而HtmlTextWriter封装了HTML写文本流的功能函数。

using System;
using System.Collections.Generic;
using System.Text;
namespace ClassLibrary1
{
public class Control1 : System.Web.UI.Control
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
writer.Write("I"m here.");
}
}
public class Control2 : System.Web.UI.WebControls.WebControl
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
writer.Write("I"m here too.");
}
}
}