Page 157 - DCAP312_WEB_TECHNOLOGIES_II
P. 157
Unit 8: Creating More Advanced ASP.NET
8.2.1 Overview Notes
An ASP.NET Web user control is similar to a complete ASP.NET Web page (.aspx file), with
both a user interface page and code. You create the user control in much the same way you
create an ASP.NET page and then add the markup and child controls that you need. A user
control can include code to manipulate its contents like a page can, including performing tasks
such as data binding.
A user controls differs from an ASP.NET Web page in these ways:
• The file name extension for the user control is .ascx.
• Instead of a @ Page directive, the user control contains an @ Control directive that defines
configuration and other properties.
• User controls cannot run as stand-alone files. Instead, you must add them to ASP.NET
pages, as you would any control.
• The user control does not have html, body, or form elements in it. These elements must
be in the hosting page.
• You can use the same HTML elements (except the html, body, or form elements) and Web
controls on a user control that you do on an ASP.NET Web page. For example, if you
are creating a user control to use as a toolbar, you can put a series of Button Web server
controls onto the control and create event handlers for the buttons.
The following example shows a user control that implements a spinner control where users can
click up and down buttons to rotate through a series of choices in a text box.
<% @ Control Language= “C#” ClassName= “UserControl1” %>
<script runat= “server”>
protected int currentColorIndex;
protected String[] colors = { “Red”, “Blue”, “Green”, “Yellow”};
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
currentColorIndex =
Int16.Parse(ViewState[ “currentColorIndex”].ToString());
}
else
{
currentColorIndex = 0;
DisplayColor();
}
}
protected void DisplayColor()
{
textColor.Text = colors[currentColorIndex];
LOVELY PROFESSIONAL UNIVERSITY 151