Asp.net 基础3(自定义控件的使用)
2010-05-12 00:16 c#在路上 阅读(293) 评论(0) 编辑 收藏 举报首先是自定义控件的实现
继承Control 添加自定义属性,然后重写Render方法,此方法用于向外输出改控件
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace OwnControl
{
public class NameControl : Control
{
private string name;
private bool isImport;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public bool IsImport
{
get
{
return isImport;
}
set
{
isImport = value;
}
}
protected override void Render(HtmlTextWriter writer)
{
string txt;
if(isImport)
txt=string.Format("<h1>{0}</h1>",name);
else
txt=string.Format("<h2>{0}</h2>",name);
writer.Write(txt);
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace OwnControl
{
public class NameControl : Control
{
private string name;
private bool isImport;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public bool IsImport
{
get
{
return isImport;
}
set
{
isImport = value;
}
}
protected override void Render(HtmlTextWriter writer)
{
string txt;
if(isImport)
txt=string.Format("<h1>{0}</h1>",name);
else
txt=string.Format("<h2>{0}</h2>",name);
writer.Write(txt);
}
}
}
把上述的文件写到单独的类工程里,编译通过。在web项目添加该项目的引用。
然后再asp.net 页面里使用该控件。
注册控件:<%@ Register Namespace="OwnControl" TagPrefix="useown" Assembly="OwnControl" %>
使用控件:<useown:NameControl ID="use1" runat="server" Name="yijianliang" IsImport="true"></useown:NameControl>
代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UseOwnControlForm.aspx.cs" Inherits="TestCodeBehind.UseOwnControlForm" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register Namespace="OwnControl" TagPrefix="useown" Assembly="OwnControl" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<useown:NameControl ID="use1" runat="server" Name="yijianliang" IsImport="true"></useown:NameControl>
<useown:NameControl ID="user2" runat="server" Name="yijianxiang" IsImport="false"></useown:NameControl>
</div>
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register Namespace="OwnControl" TagPrefix="useown" Assembly="OwnControl" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<useown:NameControl ID="use1" runat="server" Name="yijianliang" IsImport="true"></useown:NameControl>
<useown:NameControl ID="user2" runat="server" Name="yijianxiang" IsImport="false"></useown:NameControl>
</div>
</form>
</body>
</html>