<p>
This is a user control…… really!
</p>
这就是一个用户控件!看到这里,我想你会说我该不是喝醉了,头脑不清楚吧。但这段代码的确就是易于被使用的一个用户控件。尽管这个控件没有作什么事,却是关于什么是用户控件的一个很好说明。事情并不象想像得那么复杂。注意后缀。ascx,它告诉网页这是一个用户控件。它没有什么特别含义,只是不让IIS去直接执行这段代码。
现在我们来创建一个用户控件,看下面的例子:
basic.aspx
<%@ Page Language="VB" %>
<%@ Register TagPrefix="asp101samps" TagName="SomeText" Src="basic.ascx" %>
<html>
<head>
<title>ASP.NET User Control Sample - Basic</title>
</head>
<script language="VB" runat="server">
Public Color As String = "black"
Public Text As String = "This is a user control…… really!"
</script>
<p>
<font color="<%= Color %>">
<%= Text %>
</font>
</p>
这样就可以使用和改变控件的色彩和文字了。可以在初始化时赋值,还可以动态地修改这二个属性。
在同一个网页里可以重复调用这个控件并使用不同的属性值:
properties.aspx
<%@ Page Language="VB" %>
<%@ Register TagPrefix="asp101samps" TagName="SomeText" Src="properties.ascx" %>
<script language="VB" runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
UserCtrl1.Color = "green"
UserCtrl1.Text = "This control's properties were set programmatically!"
End Sub
</script>
<html>
<head>
<title>ASP.NET User Control Sample - Properties</title>
</head>
<script language="VB" runat="server">
Sub Page_Load(Src As Object, E As EventArgs)
Dim strInitialText As String = "Please Enter a Name!"
If Page.IsPostBack Then
If txtName.Text = strInitialText
txtName.Text = ""
End If
Else
txtName.Text = strInitialText
End If
End Sub
Public Property Name As String
Get
Return txtName.Text
End Get
Set
txtName.Text = Value
End Set
End Property
</script>
Please Enter a Name!
</asp:RequiredFieldValidator>
events.aspx
<%@ Page Language="VB" ClientTarget="downlevel" %>
<%@ Register TagPrefix="asp101samps" TagName="SomeText" Src="properties.ascx" %>
<%@ Register TagPrefix="asp101samps" TagName="TextBox" Src="events.ascx" %>
<script language="VB" runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
txtLabel.Text = ""
' The textbox control handles it's own stuff
' in it's own Page_Load event handler.
End Sub
Sub btnSubmit_Click(Sender As Object, E As EventArgs)
' Sets the label to the textbox's text
txtLabel.Text = txtName.Name
' I don't need to worry about validation since
' my user control does it for me.
End Sub
</script>
<html>
<head>
<title>ASP.NET User Control Sample - Validation & Events</title>
</head>