ASP.NET Tutorial/Custom Controls/Basics
Содержание
- 1 Action from user-defined control
- 2 Adding controls to the Web user control
- 3 ASP controls in user control
- 4 A Web user control file template
- 5 Building a simple User control that randomly displays one image
- 6 Building Fully Rendered Controls
- 7 Calculator component based on page component (VB.net)
- 8 Component level variable
- 9 Creating control events in a user control (C#)
- 10 Creating control events in a user control (VB)
- 11 Day minder page component
- 12 Exposing user control properties (C#)
- 13 Exposing user control properties (VB)
- 14 Pass parameter from user-defined controls to host page
- 15 Populating user control properties from the host Web page (C#)
- 16 Populating user control properties from the host Web page (VB)
- 17 Registering User Controls in the Web Configuration File
- 18 Use custom control in Assembly
- 19 User control with property
Action from user-defined control
File: Control.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Control.ascx.cs" Inherits="LinkMenu" %>
<div>
Products:
<asp:HyperLink id="lnkBooks" runat="server"
NavigateUrl="MenuHost.aspx?product=Books">Books
</asp:HyperLink><br />
<asp:HyperLink id="lnkToys" runat="server"
NavigateUrl="MenuHost.aspx?product=Toys">Toys
</asp:HyperLink><br />
<asp:HyperLink id="lnkSports" runat="server"
NavigateUrl="MenuHost.aspx?product=Sports">Sports
</asp:HyperLink><br />
<asp:HyperLink id="lnkFurniture" runat="server"
NavigateUrl="MenuHost.aspx?product=Furniture">Furniture
</asp:HyperLink>
</div>
File: Control.ascx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class LinkMenu : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
File: MenuHost.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="MenuHost.aspx.cs" Inherits="MenuHost"%>
<%@ Register TagPrefix="nfex" TagName="LinkMenu" Src="Control.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Menu Host</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table >
<tr>
<td style="width: 100px">
<nfex:LinkMenu id="Menu1" runat="server" />
</td>
<td>
<asp:Label id="lblSelection" runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
File: MenuHost.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class MenuHost : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["product"] != null)
{
lblSelection.Text = "You chose: ";
lblSelection.Text += Request.Params["product"];
}
}
}
Adding controls to the Web user control
<%@ Control Language="VB" ClassName="WebUserControl2" %>
<script runat="server">
</script>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" />
ASP controls in user control
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register Src="Control.ascx" TagName="VaryByControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:VaryByControl ID="VaryByControl1" runat="server" />
</div>
</form>
</body>
</html>
File: Control.ascx
<%@ Control Language="C#"
AutoEventWireup="true"
CodeFile="Control.ascx.cs"
Inherits="VaryByControl" %>
<%@ OutputCache Duration="30" VaryByControl="lstMode" %>
<asp:DropDownList id="lstMode" runat="server" Width="187px">
<asp:ListItem>Large</asp:ListItem>
<asp:ListItem>Small</asp:ListItem>
<asp:ListItem>Medium</asp:ListItem>
</asp:DropDownList> <br />
Control generated at:<br />
<asp:label id="TimeMsg" runat="server" />
File: Control.ascx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class VaryByControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
switch (lstMode.SelectedIndex)
{
case 0:
TimeMsg.Font.Size = FontUnit.Large;
break;
case 1:
TimeMsg.Font.Size = FontUnit.Small;
break;
case 2:
TimeMsg.Font.Size = FontUnit.Medium;
break;
}
TimeMsg.Text = DateTime.Now.ToString("F");
}
}
A Web user control file template
<%@ Control Language="VB" ClassName="WebUserControl1" %>
<script runat="server">
</script>
Building a simple User control that randomly displays one image
Both the UserControl class and the Page class derive from the base TemplateControl class.
Custom control is stored in the file with .ascx extension.
You cannot request this file directly from a web browser.
Before using a web User control, you must register it.
<%@ Register %> directive contains the three attributes:
TagPrefix: namespace. You can use any string that you want.
TagName: name that you want to associate with the User control.
Src: virtual path to the User control (the path to the .ascx file).
File: Control.ascx
<%@ Control Language="C#" ClassName="RandomImage" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
void Page_Load()
{
string imageToDisplay = GetRandomImage();
imgRandom.ImageUrl = Path.rubine("~/Images", imageToDisplay);
lblRandom.Text = imageToDisplay;
}
private string GetRandomImage()
{
Random rnd = new Random();
string[] images = Directory.GetFiles(MapPath("~/Images"), "*.jpg");
string imageToDisplay = images[rnd.Next(images.Length)];
return Path.GetFileName(imageToDisplay);
}
</script>
<asp:Image
id="imgRandom"
Width="300px"
Runat="server" />
<br />
<asp:Label
id="lblRandom"
Runat="server" />
File: ShowRandomImage.aspx
<%@ Page Language="C#" %>
<%@ Register TagPrefix="user" TagName="RandomImage" Src="~/Control.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show RandomImage</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<user:RandomImage
ID="RandomImage1"
Runat="server" />
</div>
</form>
</body>
</html>
Building Fully Rendered Controls
File: FullyRenderedControl.cs
namespace myControls
{
public class FullyRenderedControl : Control
{
private string _Text;
public string Text
{
get { return _Text; }
set { _Text = value; }
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write(_Text);
}
}
}
File: Default.aspx
<%@ Page Language="C#" %>
<%@ Register TagPrefix="custom" Namespace="myControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show Fully Rendered Control</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<custom:FullyRenderedControl
ID="FullyRenderedControl1"
Text="Hello World!"
runat="Server" />
</div>
</form>
</body>
</html>
Calculator component based on page component (VB.net)
File: index.aspx
<%@ Page language="VB" %>
<%@ Register TagPrefix="nfexASP" TagName="Calculator" src="Control.ascx" %>
<html><body>
<form runat="server">
<nfexASP:Calculator id="Calc1" runat="server"/>
</form>
</body></html>
File: Control.ascx
<script language="VB" runat="server">
private answer as double
Sub btOperator_Click(Sender as Object, e as EventArgs)
if (hiddenvalue.value <> "" and hiddenvalue.value <> "0")
tbNumber.Text = Operate(Sender.Text, hiddenvalue.value, tbNumber.Text)
hiddenvalue.value = ""
hiddenoperator.value = ""
else
hiddenvalue.value = tbNumber.Text
hiddenoperator.value = Sender.Text
tbNumber.Text = "0"
end if
End Sub
Sub btSpecOperator_Click(Sender as Object, e as EventArgs)
tbNumber.Text = Operate(Sender.Text, hiddenvalue.value, tbNumber.Text)
hiddenvalue.value = ""
hiddenoperator.value = ""
End Sub
Sub btNumber_Click(Sender as Object, e as EventArgs)
response.write(answer.ToString)
if tbNumber.Text <> "0" then
tbNumber.Text = tbNumber.Text & Sender.Text
else
tbNumber.Text = Sender.Text
answer = nothing
end if
end sub
Sub btClear_Click(Sender as Object, e as EventArgs)
tbNumber.Text = "0"
hiddenoperator.value = ""
hiddenvalue.value = ""
end sub
Sub btBS_Click(Sender as Object, e as EventArgs)
if tbNumber.Text <> "0" then
tbNumber.Text = Left(tbNumber.Text, len(tbNumber.Text)-1)
end if
end sub
Sub btMemory_Click(Sender as Object, e as EventArgs)
select case Sender.text
case "MC"
Session("memory") = ""
Indicator.Text = ""
case "MS"
Session("memory") = tbNumber.Text
Indicator.Text = "M"
case "MR"
tbNumber.Text = Session("Memory")
case "M+"
end select
end sub
Sub btEqual_Click(Sender as object, e as EventArgs)
if hiddenvalue.value <> "" then
if hiddenoperator.value <> "" then
tbNumber.Text = Operate(hiddenoperator.value, hiddenvalue.value, tbNumber.Text)
hiddenvalue.value = ""
hiddenoperator.value = ""
answer = tbNumber.Text
else
"do nothing
end if
else
"do nothing
end if
end sub
private function Operate(op as string, number1 as string, number2 as string ) as double
select case op
case "+"
Operate = CDbl(number1) + CDbl(number2)
case "-"
Operate = CDbl(number1) - CDbl(number2)
case "*"
Operate = CDbl(number1) * CDbl(number2)
case "/"
Operate = CDbl(number1) / CDbl(number2)
case "sqrt"
Operate = CDbl(Math.sqrt(number2))
case "1/x"
Operate = CDbl(1 / cdbl(number2))
case "+/-"
Operate = CDbl(-cdbl(number2))
end select
end function
</script>
<asp:Panel id="Frame" runat="server">
<table width="250">
<tr>
<td width="100%" colspan="7">
<asp:textbox id="tbNumber" runat=server
text="0"
enabled="false"
width="100%" />
</td>
</tr>
<tr>
<td align="right" width="100%" colspan="7">
<asp:Label id="Indicator" text="" runat="server" />
<asp:button id="btBS" Text="Backspace"
OnClick="btBS_Click" runat=server width="75"/>
<asp:button id="btClear" Text="C"
OnClick="btClear_Click" runat=server width="35"/>
</td>
</tr>
<tr>
<td width="32" valign="top">
<asp:button id="btMC" Text="MC"
OnClick="btMemory_Click" runat=server
width="35"/>
</td>
<td width="58"></td>
<td width="32">
<asp:button id="bt7" Text="7"
OnClick="btNumber_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="bt8" Text="8"
OnClick="btNumber_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="bt9" Text="9"
OnClick="btNumber_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="btDivide" Text="/"
OnClick="btOperator_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="btSqrt" Text="sqrt"
OnClick="btSpecOperator_Click" runat=server
width="35"/>
</td>
</tr>
<tr>
<td width="32" valign="top">
<asp:button id="btMR" Text="MR"
OnClick="btMemory_Click" runat=server
width="35"/>
</td>
<td width="8"></td>
<td width="32">
<asp:button id="bt4" Text="4"
OnClick="btNumber_Click"
runat=server width="35"/>
</td>
<td width="32">
<asp:button id="bt5" Text="5"
OnClick="btNumber_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="bt6" Text="6"
OnClick="btNumber_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="btMultiply" Text="*"
OnClick="btOperator_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="btPercent" Text="%"
OnClick="btOperator_Click" runat=server
width="35"/>
</td>
</tr>
<tr>
<td width="32" valign="top">
<asp:button id="btMS" Text="MS"
OnClick="btMemory_Click" runat=server
width="35"/>
</td>
<td width="8"></td>
<td width="32">
<asp:button id="bt1" Text="1"
OnClick="btNumber_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="bt2" Text="2"
OnClick="btNumber_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="bt3" Text="3"
OnClick="btNumber_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="btSubtract" Text="-"
OnClick="btOperator_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="btOneOver" Text="1/x"
OnClick="btSpecOperator_Click" runat=server
width="35"/>
</td>
</tr>
<tr>
<td width="32" valign="top">
<asp:button id="btMP" Text="M+"
OnClick="btMemory_Click" runat=server
width="35"/>
</td>
<td width="8"></td>
<td width="32">
<asp:button id="bt0" Text="0"
OnClick="btNumber_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="btNegate" Text="+/-"
OnClick="btSpecOperator_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="btDot" Text="."
OnClick="btNumber_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="btAdd" Text="+"
OnClick="btOperator_Click" runat=server
width="35"/>
</td>
<td width="32">
<asp:button id="btEqual" Text="="
OnClick="btEqual_Click" runat=server
width="35"/>
</td>
</tr>
</table>
</asp:Panel>
<input type="hidden" id="hiddenvalue" value=""
runat="server" >
<input type="hidden" id="hiddenoperator" value=""
runat="server" >
Component level variable
<%@Import Namespace="System.Drawing" %>
<%@Register TagPrefix="CodingStrategies" TagName="Color" Src="Control.ascx" %>
<script language="C#" runat="server">
protected void SetColor(object o, EventArgs e) {
Color color = Color.FromName(theTextbox.Text);
colorControl.Color = color;
}
</script>
<form runat="server">
Name your favorite color
<asp:textbox runat="server" id="theTextbox" OnTextChanged="SetColor" Value="Black"/><br />
Your favorite color is: <CodingStrategies:Color runat="server" id="colorControl" /><br />
<asp:button type="submit" runat="server" Text="Go" />
</form>
File: Control.ascx
<%@Import namespace="System.Drawing" %>
<script runat="server" language="C#">
protected Color favoriteColor = Color.Black;
protected void Page_Load(Object o, EventArgs e) {
theLabel.Text = favoriteColor.Name;
}
public Color Color {
set {
favoriteColor = value;
theLabel.Text = favoriteColor.Name;
theLabel.ForeColor = favoriteColor;
}
}
</script>
<h2><asp:label id="theLabel" runat="server"/></h2>
Creating control events in a user control (C#)
<%@ Control Language="C#" ClassName="WebUserControl1" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
this.Label1.Text = "The quick brown fox jumped over the lazy dog";
}
protected void Button1_Click(object sender, EventArgs e)
{
this.Label1.Text = "The quick brown fox clicked the button on the page";
}
</script>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Creating control events in a user control (VB)
<%@ Control Language="VB" ClassName="WebUserControl1" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Me.Label1.Text = "The quick brown fox jumped over the lazy dog"
End Sub
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Me.Label1.Text = "The quick brown fox clicked the button on the page"
End Sub
</script>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Day minder page component
<%@ Page Language="VB" debug="true" %>
<%@ Register TagPrefix="nfexASP" TagName="Planner" src="Control.ascx" %>
<html><body>
<form runat="server">
<nfexASP:Planner id="Planner" runat="server" />
</form>
</body></html>
File: Control.ascx
<script language="VB" runat="server">
Public sub Page_Load(Sender as Object, e as EventArgs)
if not Page.IsPostBack then
Session.Clear
Calendar1.SelectedDate = DateTime.Now
DayLabel.Text = Calendar1.SelectedDate. _
ToString("dddd, MMMM dd yyyy")
end if
End Sub
Public sub SelectionChanged(Sender as Object, e as EventArgs)
DayLabel.Text = Calendar1.SelectedDate. _
ToString("dddd, MMMM dd yyyy")
if not (Session(Calendar1.SelectedDate.ToString) is nothing)
dim l as Label = new label
l.Text = Session(Calendar1.SelectedDate.ToString)
DayPanel.Controls.Add(l)
end if
End Sub
Public sub NoteChanged(Sender as Object, e as EventArgs)
if Sender.text <> "" then
dim l as Label = New Label
l.text = "<li>" & Sender.Text & "</li>"
DayPanel.Controls.Add(l)
Session(Calendar1.SelectedDate.ToString) = l.text
NoteBox.Text = ""
end if
End Sub
</script>
<table width="100%">
<tr>
<td width="50%" valign="top">
<font face="arial">
<asp:Label id="DayLabel"
runat="server"
Height="25px"
Width="100%"
BackColor="blue"
ForeColor="white"
Font-Bold="true"/>
<br>
<asp:Panel id="DayPanel"
runat="server"
backcolor="#ffffff"
Height="225px" >
<asp:Textbox id="NoteBox"
runat="server"
OnTextChanged="NoteChanged"
TextMode="Multiline"
Rows=5
Width="100%"
AutoPostBack="true" />
</asp:Panel>
</font>
</td>
<td width="50%" rowspan="2" valign="top">
<asp:Calendar id="Calendar1"
runat="server"
OnSelectionChanged="SelectionChanged"
Cellpadding="5"
Cellspacing="5"
DayHeaderStyle-Font-Bold="True"
DayNameFormat="Short"
Font-Name="Arial"
Font-Size="12px"
height="250px"
NextPrevFormat="ShortMonth"
NextPrevStyle-ForeColor="white"
SelectedDayStyle-BackColor="#ffcc66"
SelectedDayStyle-Font-Bold="True"
SelectionMode="DayWeekMonth"
SelectorStyle-BackColor="#99ccff"
SelectorStyle-ForeColor="navy"
SelectorStyle-Font-Size="9px"
ShowTitle="true"
TitleStyle-BackColor="#ddaa66"
TitleStyle-ForeColor="white"
TitleStyle-Font-Bold="True"
TodayDayStyle-Font-Bold="True" />
</td>
</tr>
</table>
Exposing user control properties (C#)
<%@ Control Language="C#" ClassName="WebUserControl" %>
<script runat="server">
private string _text;
public string Text
{
get {
return _text;
}
set {
_text = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
this.Label1.Text = this.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
this.Label1.Text = "The quick brown fox clicked the button on the page";
}
</script>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Exposing user control properties (VB)
<%@ Control Language="VB" ClassName="WebUserControl" %>
<script runat="server">
Private _text As String
Public Property Text() As String
Get
Return _text
End Get
Set(ByVal value As String)
_text = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Me.Label1.Text = Me.Text
End Sub
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Me.Label1.Text = "The quick brown fox clicked the button on the page"
End Sub
</script>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Pass parameter from user-defined controls to host page
File: Control.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Control.ascx.cs" Inherits="Control" %>
<div>
Products:
<asp:LinkButton ID="lnkBooks" runat="server" CommandArgument="MenuHost.aspx?product=Books" OnCommand="lnk_Command" >Books
</asp:LinkButton><br />
<asp:LinkButton ID="lnkToys" runat="server" CommandArgument="MenuHost.aspx?product=Toys" OnCommand="lnk_Command">Toys
</asp:LinkButton><br />
<asp:LinkButton ID="lnkSports" runat="server" CommandArgument="MenuHost.aspx?product=Sports" OnCommand="lnk_Command">Sports
</asp:LinkButton><br />
<asp:LinkButton ID="lnkFurniture" runat="server" CommandArgument="MenuHost.aspx?product=Furniture" OnCommand="lnk_Command">Furniture
</asp:LinkButton>
</div>
File: Control.ascx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class LinkMenu : System.Web.UI.UserControl
{
public event LinkClickedEventHandler LinkClicked;
protected void lnk_Command(object sender, CommandEventArgs e)
{
if (LinkClicked != null)
{
LinkClickedEventArgs args = new LinkClickedEventArgs((string)e.rumandArgument);
LinkClicked(this, args);
if (!args.Cancel)
{
Response.Redirect(args.Url);
}
}
}
}
File: MenuHost.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="MenuHost.aspx.cs" Inherits="MenuHost"%>
<%@ Register TagPrefix="nfex" TagName="LinkMenu" Src="Control.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Menu Host</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td style="width: 100px">
<nfex:LinkMenu id="Menu1" runat="server" OnLinkClicked="LinkClicked" />
</td>
<td>
<asp:Label id="lblSelection" runat="server" EnableViewState="false"/><br />
<asp:Label id="lblClick" runat="server" EnableViewState="false"/>
</td>
</tr>
</table>
<br />
</div>
</form>
</body>
</html>
File: MenuHost.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public class LinkClickedEventArgs : EventArgs
{
private string url;
public string Url
{
get { return url; }
set { url = value; }
}
private bool cancel = false;
public bool Cancel
{
get { return cancel; }
set { cancel = value; }
}
public LinkClickedEventArgs(string url)
{
Url = url;
}
}
public delegate void LinkClickedEventHandler(object sender, LinkClickedEventArgs e);
public partial class MenuHost : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.Params["product"] != null)
{
lblSelection.Text = "You chose: ";
lblSelection.Text += Request.Params["product"];
}
}
}
protected void LinkClicked(object sender, LinkClickedEventArgs e)
{
if (e.Url == "MenuHost.aspx?product=Furniture")
{
lblClick.Text = "This link is not allowed.";
e.Cancel = true;
}
}
}
Populating user control properties from the host Web page (C#)
<%@ Page Language="C#" %>
<%@ Register Src="Control.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
this.WebUserControl1.Text = "The quick brown fox jumped over the lazy dog";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl id="WebUserControl1" runat="server">
</uc1:WebUserControl></div>
</form>
</body>
</html>
File: Control.ascx
<%@ Control Language="C#" ClassName="WebUserControl" %>
<script runat="server">
private string _text;
public string Text
{
get {
return _text;
}
set {
_text = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
this.Label1.Text = this.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
this.Label1.Text = "The quick brown fox clicked the button on the page";
}
</script>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Populating user control properties from the host Web page (VB)
<%@ Page Language="VB" %>
<%@ Register Src="Control.ascx" TagName="WebUserControl"
TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Me.WebUserControl1.Text = "The quick brown fox jumped over the lazy dog"
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
</div>
</form>
</body>
</html>
File: Control.ascx
<%@ Control Language="VB" ClassName="WebUserControl" %>
<script runat="server">
Private _text As String
Public Property Text() As String
Get
Return _text
End Get
Set(ByVal value As String)
_text = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Me.Label1.Text = Me.Text
End Sub
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Me.Label1.Text = "The quick brown fox clicked the button on the page"
End Sub
</script>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Registering User Controls in the Web Configuration File
File: Control.ascx
<%@ Control Language="C#" ClassName="RandomImage" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
void Page_Load()
{
string imageToDisplay = GetRandomImage();
imgRandom.ImageUrl = Path.rubine("~/Images", imageToDisplay);
lblRandom.Text = imageToDisplay;
}
private string GetRandomImage()
{
Random rnd = new Random();
string[] images = Directory.GetFiles(MapPath("~/Images"), "*.jpg");
string imageToDisplay = images[rnd.Next(images.Length)];
return Path.GetFileName(imageToDisplay);
}
</script>
<asp:Image
id="imgRandom"
Width="300px"
Runat="server" />
<br />
<asp:Label
id="lblRandom"
Runat="server" />
File: Web.Config
<configuration>
<system.web>
<pages>
<controls>
<add
tagPrefix="user"
tagName="RandomImage"
src="~/UserControls/Control.ascx"/>
</controls>
</pages>
</system.web>
</configuration>
After you register a User control in the web configuration file, you can declare the User control in any page.
File: Default.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show Application Register</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<user:RandomImage
ID="RandomImage1"
Runat="Server" />
</div>
</form>
</body>
</html>
Use custom control in Assembly
<%@ Page Language="VB" %>
<%@ Register TagPrefix="nfexASP" Namespace="MyCustomControls" Assembly="CustomControls"%>
<html><body>
<form runat=server>
The custom control produces the following output:
<nfexASP:CustomControl1 id="MyControl" runat=server/>
</form>
</body></html>
//////C#
using System;
using System.Web;
using System.Web.UI;
namespace MyCustomControls {
public class CustomControl1 : Control {
protected override void Render(HtmlTextWriter Output) {
Output.Write("This is my custom control! ");
}
}
}
//////VB
Imports System
Imports System.Web
Imports System.Web.UI
Namespace MyCustomControls
Public Class CustomControl1 : Inherits Control
Protected Overrides Sub Render(Output as HtmlTextWriter)
Output.Write("This is my custom control! ")
End Sub
End Class
End Namespace
User control with property
<%@ Page Language="C#" %>
<%@ Register TagPrefix="apress" TagName="TimeDisplay" Src="Control.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<apress:TimeDisplay id="TimeDisplay1"
Format="dddd, dd MMMM yyyy HH:mm:ss tt (GMT z)" runat="server" />
<hr />
<apress:TimeDisplay id="TimeDisplay2" runat="server" />
</div>
</form>
</body>
</html>
File: Control.ascx
<%@ Control Language="C#"
AutoEventWireup="true"
CodeFile="Control.ascx.cs"
Inherits="TimeDisplay" %>
<br />
<asp:LinkButton runat="server" ID="lnkTime" OnClick="lnkTime_Click"/>
File: Control.ascx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class TimeDisplay : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
RefreshTime();
}
protected void lnkTime_Click(object sender, EventArgs e)
{
RefreshTime();
}
public void RefreshTime()
{
if (format == "")
{
lnkTime.Text = DateTime.Now.ToLongTimeString();
}
else
{
lnkTime.Text = DateTime.Now.ToString(format);
}
}
private string format;
public string Format
{
get { return format; }
set { format = value; }
}
}