Sie sind auf Seite 1von 26

Color profile: Generic CMYK printer profile

All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Server Controls
in ASP.NET
CHAPTER

14
In this chapter, you will
• Add web server controls, HTML server controls, user controls, and HTML
code to ASP.NET pages
• Create custom controls and user controls
• Load controls dynamically

Now that we have defined the event and postback architecture of the Web Form, we can
start looking at some of the more exciting components that are included with ASP.NET.
In this chapter you will learn about the different server controls and how they are ren-
dered as HTML to the client, and how ASP.NET is taking care to render HTML that will
work different platforms by carefully using only the lowest common denominator stan-
dards for each browser.

We will also work with user controls and build our own special controls to simplify
the processing of data and centralize the functionality for a group of controls.

Working with ASP Controls


The building blocks of our Web Forms are the controls that give us the ability to display
data to the user, as well as enabling the user to interact with the application. There are a
couple of families of controls available for use in ASP.NET Web Forms: there are the tra-
ditional HTML controls that can be used as is, with no further involvement from the
server, and there are the intrinsic HTML controls that use a server control to encapsulate
the HTML control (rich controls), giving us a richer object model to work with.
In the ASP.NET environment we have validation controls that we can use to validate
the data from the user, and we looked at the use of these controls in Chapter 12. What
this section will add to the control pallet is the use of the so-called rich controls. These are
controls with no direct HTML counterpart—they are combinations of different intrinsic
controls that form a functional unit.
ASP.NET automatically senses the browser version and manufacturer used by the cli-
ent, and it renders the server controls properly for that browser. This means you do not

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:21 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
All-In-One
screen / MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
14
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


2
have to produce a “least common denominator” version of your site or have multiple
versions for different browsers. For example, we do not have to produce one version of
our web site for each browser on the market; ASP.NET provides support to generate
HTML that is browser specific taking care not to send HTML elements that are not
supported in the browser. In some cases the generated HTML code is the same as is the
case with the ListBox control that would be rendered in the same fashion by both
Netscape and Internet Explorer, while the Calendar control would be rendered totally
different between the different browsers.
Your Web Forms can be configured to meet a lowest-common-denominator
browser by changing the setting for TargetSchema on the document object, as
shown in Figure 14-1. You would change this setting to the lowest browser version that
you must support; Internet Explorer 5 is the default for this property. Set this property
based on the expected client base—if the site will be used on the Internet, you could set
it to a version 4 browser; for an intranet you could set a very specific, high-version
browser.

Figure 14-1
Changing the
TargetSchema
for the
Web Form

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:21 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


3
Base Properties of Server Controls
All the server controls have a common set of base properties, in addition to their specific
properties. The base properties are used to control the look and feel of the control.
Table 14-1 lists the more commonly used base properties and outlines their use.
These are just a few of the properties that are available to us in Visual Studio .NET. Al-
though there are more properties than some browsers can support, the .NET Framework
will render the control based on the target browser, ensuring that the page will look
okay in any browser.
The following Label control uses some of the properties for the control:

<asp:Label id="Label1" runat="server" Height="80px" Width="320px"


BackColor="DodgerBlue" BorderStyle="Ridge" BorderWidth="6px"
Font-Names="Kristen ITC" Font-Size="XX-Large" >
Hello World!</asp:Label>

PART III
The Label control is actually rendered as an HTML span for both Netscape and
Internet Explorer. The HTML for Internet Explorer looks like this:

<span id="Label1" style="background-color:DodgerBlue; border-width:6px;


border-style:Ridge; font-family:Kristen ITC; font-size:XX-Large;
height:80px; width:320px; LEFT: 10px; POSITION: absolute; TOP: 15px">
Hello World!</span>

Description
BackColor Sets the background color of the control. This property can be set to any of
the color constants in the .NET Framework’s Color structure property,
such as DodgerBlue, AntiqueWhite, or to hexadecimal literal values like
#C8C8C8 (gray).
BorderWidth Sets the width of the control’s border, in pixels.
Enabled Determines whether or not the control is available for user interaction. If this
property is set to False, the control will be grayed out and the control will not
process any event until the Enabled property has been set to True.
Font Controls the appearance of the text in the control. This property has a
number of subproperties, such as Size, which specifies the size of the font;
Name, which specifies the name of the font; and Bold, which can be set to
True or False to make the font bold or not.
ForeColor Determines the color of the text in the control.
Height Sets the height of the control.
ToolTip Specifies the text to be displayed beside the control when the user keeps the
mouse pointer near the control. This property is one of the ways we can use
to actually teach our users how to use our web site.
Visible Determines whether the control is visible (True) or hidden (False). Use this
property to hide controls that are not initially needed, and then display them
based on the user’s selections.
Width Sets the width of the control.
Table 14-1 The Most Commonly Used Base Properties for Server Controls

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:21 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


4
The HTML rendered for the Netscape browser is tailored for that browser’s special abilities:

<span id="Label1" style="LEFT: 10px; POSITION: absolute; TOP: 15px">


<font face="Kristen ITC" size="7">
Hello World!
</font>
</span>

The power of writing one code module that will work with most browsers is im-
mense; we can focus on the development task rather than on the minute differences be-
tween the browsers.

EXAM TIP The .NET Framework renders the server control based on the
user’s browser.

HTML Server Controls


Here we will have a look at the intrinsic controls, also known as ASP Server Controls,
that are encapsulations of the standard HTML controls, listed in Table 14-2. These con-
trols are mostly rendered using the equivalent underlying HTML element.

HTML
Equivalent Description
Button Button This is the common command button. It uses the Click
event to communicate with the application.
CheckBox Checkbox CheckBox is the control you will use for Yes or No
selections.
DropDownList Select DropDownList is used for making a selection from many
different values.
Hyperlink Anchor The Hyperlink is used as a button, but the display is
an Anchor.
Image Img Image is used to display a picture.
Label span Label is used to display descriptive text as well as read-only
information.
ListBox select This is a control that allows the user to select an item
in a list. The ListBox control can optionally allow multiple
selections.
Panel div The Panel gives us an area in the page that can be used
to group controls and treat them as one.
RadioButton Option RadioButton is used for mutually exclusive selections.
Table table This control is used to create an HTML table.
TableCell td This is a cell in a table.
TableRow tr This is a row in a table.
TextBox text This is the control to use when the user needs to enter
information on the web page. The control will be rendered
as a text input control.
Table 14-2 The Intrinsic Server Controls

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:21 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


5
We covered event handling and registration in detail in Chapter 11, and we’ll see it
put to use in the following example. In this example you will build a Web Form where
you will see the code that connects a control with its event handler. Start a new Visual C#
project, select an ASP.NET Web Application template, call the project Button1 on the
localhost server.
After the project is created open the HTML view of the web page. We will use a server
control to insert an element in the HTML part of the Web Form file (.aspx) as we’ve
done for the Button control in the following line of HTML code:

<asp:Button id="TheButton" runat="server" />

The Button control can have events connected to it, and there are two possible
ways of performing that linking: either by registering an event handler in the
InitializeComponent() method that will run when the Web Form is initially cre-

PART III
ated, or by adding the attribute to the control when it is defined. The following code
line defines the event handler in the Button definition:

<asp:Button id="TheButton" runat="server" OnClick="buttonClick" />

The event handler for the Click event is defined as buttonClick(). OnClick is the
keyword that tells ASP.NET that we are talking about the Click event.
Expand the code display and locate the InitializeComponent() method. The
code to register the event will look like this:

this.TheButton.Click += new System.EventHandler(this.button_Click);

After we have added the button and wired the event handling for it, we need to look
at a new control that is used to group other controls in the web page.
One very useful server control is the Panel, which gives us the ability to handle
groups of controls in the same way by using common code for the controls rather than
writing individual event handlers. In this next example we will use a number of different
controls to create a converter application that will convert from km/h to mph. We will
work through the Visual Studio .NET IDE to build an application named Panel1 on the
localhost server. The user interface of the application is created as in Figure 14-2.
To place all the controls, we used the following code for the HTML portion of the form:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"


Inherits="Panel1.WebForm1" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >


<HTML>
<HEAD>
<title>WebForm1</title>

</HEAD>
<body MS_POSITIONING="GridLayout">
<h1>The speed converter</h1>
<form id="Form1" method="post" runat="server">
<asp:Panel
id="Panel1" runat="server" Width="352px" Height="56px"
BackColor="Silver" BorderStyle="Ridge" BorderWidth="4px">&nbsp;

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:22 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


6
<asp:Label id="Label1" runat="server" Width="24px">mph</asp:Label>
<asp:TextBox id="TextBox1" runat="server" Width="112px"></asp:TextBox>
<asp:Label id="Label2" runat="server">km/h</asp:Label>
<asp:TextBox id="TextBox2" runat="server" Width="112px"></asp:TextBox>
</asp:Panel>
<asp:Button id="Button1" runat="server" Text="Convert"></asp:Button>
</form>
</body>
</HTML>

The bold code in the preceding listing shows how the Panel control encapsulates the
other controls that are in the panel. Note that the spaces that are inserted are there to aid
in the layout of the panel so the controls will be spaced out rather than bunched up.
The processing for the converter is configured to use the Click event from the but-
ton to convert from mph to km/h. The event handler for the button in the codebehind
module will look like this:

private void Button1_Click(object sender, System.EventArgs e)


{
TextBox2.Text = Convert.ToString(Convert.ToDouble(TextBox1.Text) * 1.6);
}

Figure 14-3 shows the application in action.


The important part of this exercise was not to build a speed converter, but rather to
look at the Panel control. The ASP.NET process converts the Panel server component
into a div HTML element that will be displayed using the client browser.

Figure 14-2 The user interface of the speed converter

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:22 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


7
Figure 14-3
The finished
speed converter

PART III
EXAM TIP The Label controls are rendered as spans. The Panel is
rendered as a div. A page using either Label or Panel controls will
display well in most browsers.

Web Server Controls


The second type of server controls is the rich controls. These are controls that have no di-
rect counterpart in HTML, and they are rendered using groups of standard controls,
varying depending on the browser. Table 14-3 lists the rich controls and describes their
usage.
These controls add functionality that is implemented by JavaScript client-side code
and standard HTML elements. As an example, we will look more closely at the
AdRotator control, which displays images as an ad banner. The images can be of any
file type that can be displayed in a browser, such as .gif, .jpg, and so on. The image
can be clickable so the user will be taken to a predetermined site for each image. What
images are displayed and how they behave is determined by an XML document that is
created using an Ad Rotator template, which we will look at shortly.
As an example, we will build a web page that uses the AdRotator control to display
“Hello World” messages in different languages each time the page is redisplayed. For
this example, the images can be created using any graphics program, as long as the di-
mensions of the different images are the same. We created five .gif files that we put in
a folder called images in the root of the application. On our server, the folder is located
at c:\inetpub\wwwroot\Rotator\images.
To start the project, create a new application named Rotator on the localhost
server. Add an AdRotator control to the Web Form as shown in Figure 14-4.
To add the images to the project, you need to create a new folder in the project called
Images and add the five .gif files to the folder. To create the new folder, right-click on

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:22 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


8
Description
AdRotator This control will display a different image each time the page is
redisplayed by the postback process.
Calendar This control displays a one-month calendar that can be customized and
used in any situation where a date display is needed.
CheckBoxList This is a grouping of CheckBox controls that forms a list, which can be
dynamically created from databases. The list is programmatically
accessible through the ID of the list.
ImageButton This control has a clickable image that may have coordinates for image
map functionality.
LinkButton This is a button displayed as a hyperlink.
RadioButtonList This is a grouping of RadioButton controls that will behave as mutually
exclusive controls. The entire list is accessible through the ID of the list.
Table 14-3 Rich Controls

the project name (Rotator) in the Project Explorer, and select Add | New Folder
from the context menu, as shown in Figure 14-5.

Figure 14-4 Adding the AdRotator control to the Web Form

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:23 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


9

PART III
Figure 14-5 Adding a folder to the project

Now you can add the images to the new folder by either dragging them there from My
Computer, or by right-clicking on the project name in the Project Explorer, selecting
Add | Add Existing Items from the context menu, and browsing for the images. The final
result should look something like what is shown in Figure 14-6.
The AdRotator has an AdvertisementFile property that determines the images to
be displayed, as well as the text version of the image for those browsers that cannot (or will
not) display graphics. The format of the AdvertisementFile is based on the Ad Rotator
template. Table 14-4 enumerates the parameters for the AdvertisementFile property.
Our example is built around a web application that has five images called ad1.gif,
ad2.gif, ad3.gif, ad4.gif, and ad5.gif. The web pages that the images are referring
to are created using the names HTMLPage1.htm, HTMLPage2.htm, HTMLPage3.htm,
HTMLPage4.htm and HTMLPage5.htm (you can find the images and HTML pages in
the Chapter 14 folder on the CD).
The AdvertisementFile is an XML document that we need to create for the
AdRotator. Follow these steps to create the AdvertisementFile:

1. Add an XML file to the project by selecting Project | Add New Item.
2. Select XML File from the Templates window, and name it Rotator.xml.
After the file is created, the XML Editor will open.

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:23 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


10
Figure 14-6
The Rotator
project with the
Images folder

3. Set the TargetSchema property for the XML file to Ad Rotator Schedule File,
as shown in Figure 14-7. Selecting the TargetSchema adds a root element of
<Advertisements> to the file.

Description
ImageUrl Specifies the URL of the image to be displayed.
NavigateUrl Specifies the URL to redirect the user to when the image is clicked.
AlternateText Contains the text to be displayed if the browser cannot display graphics.
Keyword Identifies the category of the ad, allowing filtering of ads.
Impressions Contains a numeric value that is used to specify how likely it is that this ad
will be displayed. The sum of all Impressions values must not exceed
2,048,000,000 – 1 (2,047,999,999). This is a technical limit.
Table 14-4 The Parameters for the AdvertisementFile Property

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:24 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


11

PART III
Figure 14-7 Setting the TargetSchema property

4. Add an <Ad> element as a child element to the <Advertisements> element


in XML file. The properties for each image are inserted in the <Ad> element.
5. To add the items from the Project Explorer, drag and drop the items into the
XML editor. Drag the image into the <Ad> node, as well as the HTML page that
corresponds to the image.
6. Add the rest of the five ads to the XML file.

When the file is completed, it should look like the following code:

<?xml version="1.0" encoding="utf-8" ?>


<Advertisements
xmlns="http://schemas.microsoft.com/AspNet/AdRotator-Schedule-File">
<Ad>
<ImageUrl>Images/ad1.gif</ImageUrl>
<NavigateUrl>http://localhost/Rotator/HTMLPage1.htm</NavigateUrl>
<AlternateText>The AD1.GIF</AlternateText>
<Keyword>Test</Keyword>
<Impressions>10</Impressions>
</Ad>
<Ad>

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:24 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


12
<ImageUrl>Images/ad2.gif</ImageUrl>
<NavigateUrl>http://localhost/Rotator/HTMLPage2.htm</NavigateUrl>
<AlternateText>The AD2.GIF</AlternateText>
<Keyword>Test</Keyword>
<Impressions>10</Impressions>
</Ad>

</Advertisements>

To add the XML AdvertisementFile to the AdRotator control, browse for it by


clicking on the ellipsis (three dots) next to the AdvertisementFile property, select
the Rotator.xml file, and click OK.
Save all the files, and then run the application by pressing the F5 key. Click the
browser’s refresh button and notice how the banner changes; click on the banner and
note that the browser displays the HTML page. The AdRotator control is rendered as
an anchor tag with an image forming the clickable area. The same rendering happens
when the file is displayed in a Netscape browser or Internet Explorer.

User Controls and Custom Controls


When we need to use the same controls in many different forms, it becomes tricky to
keep them all updated to have the same functionality while also repairing any unsched-
uled features (a.k.a. bugs) in the code. There are two technologies that we can employ to
build reusable controls that can be treated as components: user controls and custom
controls. User controls are scripted server controls—really converted ASP.NET pages. Cus-
tom controls are compiled into .NET assemblies that can be used wherever a control is
needed.
We will start by looking at user controls; custom controls will be discussed later in
this section.

Building and Using a User Control


A user control is a Web Form that has been converted into a reusable component that
can be used by different Web Forms. If you use a grouping of controls in many different
Web Forms, such as a voting control, you can build one user control that can be used in
all the Web Forms. First let’s look at how we can build a user control from scratch.
In this example you will build a user control that combines a Calendar control and
a TextBox to form one control. To create the user control, start a new project on the
localhost server and call it UserTest. Once the project has been created, add the user
control by selecting Project | Add New Item. This displays the Add New Item dialog box—
select the Web User Control template, and call the file WUCUser.ascx, as shown here.

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:24 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


13

PART III
The files that are added to the project are similar to the files that make up a Web
Form: there is the form file (.ascx) and the codebehind file (.ascx.cs). You’ll need
to add some controls to the user control so it will perform some function, so add a Cal-
endar and a TextBox control to the form, as shown in Figure 14-8.
The HTML code for the user control should be as follows:

<%@ Control Language="c#" AutoEventWireup="false"


Codebehind="WUCUser.ascx.cs" Inherits="UserTest.WUCUser"
TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
<P>
<asp:Calendar id="Calendar1" runat="server"></asp:Calendar>
</P>
<P>
<asp:TextBox id="TextBox1" runat="server" Width="248px"></asp:TextBox>
</P>

To be able to use the user control in our Web Form, we need to add a <%@ Register
%> directive to the WebForm1.aspx file. The directive should look like this:

<%@ Register TagPrefix="WUC" TagName="UserControl1" Src="WUCUser.ascx" %>

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:25 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


14

Figure 14-8 The WUCUser control

The Register directive lets us specify how we will refer to the user control, and the
TagPrefix and TagName are taken together to form the name of the element,
<WUC:UserControl1 />, that we will use in the form to display the control.
The HTML listing for WebForm1.aspx follows, with the additions in bold.

<%@ Register TagPrefix="WUC" TagName="UserControl1" Src="WUCUser.ascx" %>


<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
Inherits="UserTest.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>WebForm1</title>

</head>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<WUC:UserControl1 runat="server" id="theUserControl" />
</form>
</body>
</html>

In the preceding code segment, the reference to the user control sets the control’s ID
to theUserControl:

<WUC:UserControl1 runat="server" id="theUserControl" />

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:25 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


15
In order to use the ID, we need a variable that is declared in the codebehind module for
the Web Form (WebForm1.aspx.cs). The following code segment shows the manual
addition we need to make to WebForm1.aspx.cs for the code to compile, with the
addition in bold.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

PART III
namespace UserTest
{
public class WebForm1 : System.Web.UI.Page
{
protected WUCUser theUserControl;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
}

#region Web Form Designer generated code



#endregion
}
}

The project can now be executed (F5) to reveal the Calendar control and the
TextBox control. There is, however, no functionality in the user control yet. You can
click on the dates as much as you want, but nothing will happen. To add functionality,
you need to add some code to the user control, namely in the SelectionChanged
event of the Calendar control so there will be feedback when the date is changed in the
control.
To add the event handler, double-click the Calendar control in the WUCUser.ascx
file’s Design view. The final code in the codebehind file (WUCUser.ascx.cs) should
look like this:

private void InitializeComponent()


{
this.Calendar1.SelectionChanged += new System.EventHandler
(this.Calendar1_SelectionChanged);
this.Load += new System.EventHandler(this.Page_Load);
}
private void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
TextBox1.Text = Calendar1.SelectedDate.ToString();
}

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:25 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


16
The event registration and handler makes the application a little more functional.
When you run the application now, you can click on a date and the TextBox will dis-
play the date that was clicked on, as you can see in the following illustration.

Although user controls are a step in the right direction, they are still essentially
scripted ASP.NET forms that are used as subforms in another Web Form. The more pow-
erful, but also somewhat more complex, custom controls are our next topic.

Building and Using a Custom Control


Custom controls are one notch up from user controls in that they are compiled into as-
semblies that can easily be deployed with the web site, or installed in the Global Assem-
bly Cache (GAC) and be available to all applications on that server. Custom controls are
built-in files with the extension .ascx.
The difference between custom controls and user controls starts with the fact that the
.ascx file does not have a user interface (UI) built by using the drag and drop functions
of Visual Studio .NET. Rather, the UI is designed in code as part of the custom control,
and thus you have full control over what is returned to the client browser at all times.
You build custom controls by inheriting from an existing control to build a derived cus-
tom control, or you can inherit from System.Web.UI.WebControls to build a full
custom control.
The different types of custom controls are used in the same way as the user controls:
by adding a <%@ Register %> directive to the top of the Web Form. The assembly that
contains the custom control should be added to the bin directory in the root of the web
application or to the GAC so that the application can find the assembly.

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:26 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


17
EXAM TIP The custom control must be added to the bin directory of the
web site or to the GAC for it to be usable by the web site.

The following directive defines a TagPrefix of WCC, a Namespace of


WCCustomWebContols, and an Assembly name of WCCustomWebControls:

<%@ Register TagName="WCC" Namespace="WCCustomWebContols"


Assembly="WCCustomWebContols" %>

Once we have moved the assembly to the bin directory and added the Register directive
to the page, we can add the custom control to the Web Form by adding a line like the
following:

<WCC:DateControl runat="server" id="theDateControl" />

PART III
The next thing we have to look at is how to build these compiled custom controls that
can be reused between projects. The example will take you through the building of a cus-
tom control that acts as a text area. We will build the example using Visual Studio .NET.
Start by creating a custom control project from the Web Control Library template,
and name it CusControl1. The project wizard builds a default control that you can
start your developments with—the project is runnable, but you need to provide the
code to use the control.
As you work on the control, you will also need a way of testing it. There are a couple
of ways of doing this: you can create a second project that uses the control, or you could
add a web application project to the custom control solution. In this example, we will
use the second technique of adding a web application project. To add the project to a so-
lution, select File | New, and in the New Project dialog box select the ASP.NET Web Ap-
plication template—ensure that the Add To Solution option is selected.
If you left everything set to the defaults, you would end up with the two projects in
different areas on the hard drive, and you’d have to copy the custom control’s assembly
to the web application’s bin directory every time you recompiled the custom control. To
make the development easier, set the properties for the custom control project to send
the output to the bin directory in the web application. To do so, follow these steps:

1. Open the Properties dialog box for the custom control by right-clicking on the
project (CusControl1) in the Solution Explorer of the custom control project.
2. Expand the Configurations Properties folder and select the Build items to find
the Output Path.
3. Set the Output Path to the location of the web application’s bin directory. In
our case that is c:\Inetpub\wwwroot\CustControlTest\bin. Make sure
you click the ellipsis (…) to enter the path.
4. In the Configuration dropdown control select All Configurations.

Once this is done, the assembly that contains the custom control will be written into
the bin directory of the web application, which is the location where the application will

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:26 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


18
search for assemblies. Setting the Configuration Properties to All Configurations means
that the Output Path will be used both for release and debug builds.
The next step is to make the web application the startup project. You do this by
right-clicking on the CustControlTest project and selecting Set as Startup Project
from the context menu.
Now you can add the following two lines to the web application’s HTML view. The
registration of the Custom Control assembly and namespace makes the control avail-
able to the web application:

<%@ Register TagPrefix="WCC" Namespace="CusControl1" Assembly="CusControl1" %>


<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
Inherits="CustControlTest.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>WebForm1</title>

</head>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<WCC:WebCustomControl1 runat="server" Text="The World's Greatest" />
</form>
</body>
</html>

The first highlighted line makes the custom control available to the application by regis-
tering the TagPrefix, Namespace, and Assembly. The application will search for
the assemblies starting in the bin directory.
Now we can run the application by pressing F5. The resulting display is shown next.

If you have run this application, you will probably be wondering why there is an er-
ror displayed in the Design view of the Web Form, even though the control is working

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:26 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


19
when you execute the application. The problem has to do with the application not
knowing about the custom control at design time. It only looks for the assembly at run
time, so what we need to do is add a reference to the control in our Web Form project.
To do so, right-click on the References folder of the web application project. Under
the .NET tab, select browse, and select the assembly to be added as shown in the follow-
ing illustration. Click Open and then OK to add the custom control to the project. Rerun
the application, and the error in the Design view should be gone and the control should
be visible instead. A second benefit that comes from adding the reference to the control
is that you can now use it in the codebehind module as well.

PART III
Now that we have created and used a custom control, we will look a little closer at
what the custom control is, and why this stock implementation that is supplied with Vi-
sual Studio .NET is behaving like a Label control. Here’s the codebehind module for
the custom control:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace CusControl1
{
[DefaultProperty("Text"),
ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
public class WebCustomControl1 : System.Web.UI.WebControls.WebControl
{
private string text;

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:26 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


20
[Bindable(true), Category("Appearance"), DefaultValue("")]
public string Text
{
get
{
return text;
}
set
{
text = value;
}
}
protected override void Render(HtmlTextWriter output)
{
output.Write(Text);
}
}
}

The bold sections of the code define the behavior of this control. For example, look at
the first attribute:

[DefaultProperty("Text"), ToolboxData("<{0}:WebCustomControl1
runat=server></{0}:WebCustomControl1>")]

This specifies that the control will have a default property (Text) and it specifies the data
for the Toolbox. In the definition for the default property we find this attribute that de-
fines the behavior of the property:

[Bindable(true), Category("Appearance"), DefaultValue("")]

The property can be bound to data, will be located in the Appearance tab in the property
page for the control, and the default value is an empty string. The last bold line in this
segment is this one:

protected override void Render(HtmlTextWriter output)

This is where the drawing code for the control is located. You need to override the Ren-
der method for all your custom controls to define how the UI portion of the control
will function.
Suppose, for instance, we want a control that reverses the string saved in the Text
property when it is written to the display. In that case, we could change the Render
method as follows:

protected override void Render(HtmlTextWriter output)


{
for (int x=Text.Length-1; x > 0; x--)
{
output.Write(Text[x]);
}
}

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:26 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


21
Using the System.Draw namespace, you can perform direct drawing in the control,
and you have full control over the way the control is rendered.

EXAM TIP The Render method must be overridden in custom controls.

Dynamic Control Creation


There will be many times when you do not know how many controls will be needed in a
form. In instances where the user can select progressive disclosure (when the amount of
data is increased based on the user’s request) designing dynamic control structures that
can be added at run time is recommended. These dynamic controls must be added to a
container control for them to be part of the Web Form; the container control will either

PART III
be the PlaceHolder control or the Panel control. Either has the ability to add Con-
trols collections dynamically.

EXAM TIP Dynamic controls are added to existing controls that can contain
collections of controls, such as PlaceHolder and Panel controls.

In this example, we will create a Web Form with a PlaceHolder control that allows
us to add additional TextBox controls to a form, depending on the selection from a
DropDownList control. To get started, create a new project on the localhost and
call it DynCntr. Then add a PlaceHolder control to the project, as well as a Label
and a DropDownList control. The layout of the final form is shown in next.

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:27 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


22
The HTML rendition of the Web Form must be configured with some special han-
dling to make the SelectedIndexChanged event trigger a postback event. The La-
bel control, as well as the DropDownList control, need some static text added. The
following code listing shows the HTML for the Web Form:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"


AutoEventWireup="false" Inherits="DynCntr.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>

</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:DropDownList id="DropDownList1" AutoPostBack="True"
style="Z-INDEX: 101; LEFT: 368px; POSITION: absolute; TOP: 16px"
runat="server">
<asp:ListItem Value="1">One</asp:ListItem>
<asp:ListItem Value="2">Two</asp:ListItem>
<asp:ListItem Value="3">Three</asp:ListItem>
<asp:ListItem Value="4">Four</asp:ListItem>
<asp:ListItem Value="5">Five</asp:ListItem>
<asp:ListItem Value="6">Six</asp:ListItem>
<asp:ListItem Value="7">Seven</asp:ListItem>
</asp:DropDownList>
<asp:Label id="Label1"
style="Z-INDEX: 102; LEFT: 216px; POSITION: absolute; TOP: 16px"
runat="server" Width="136px">How many Controls?</asp:Label>
<asp:PlaceHolder id="PlaceHolder1" runat="server"></asp:PlaceHolder>
</form>
</body>
</HTML>

The bold sections in the preceding code were added after the controls were positioned
using the Design view.
The dynamic behavior for the application comes from the SelectedIndexChanged
event handler for the DropDownList control. The following code segment shows how
you can add controls dynamically to a Web Form:

private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)


{
// convert the value of the control to an integer
int i = Convert.ToInt32(DropDownList1.SelectedItem.Value) - 1;

// loop as many times as the user selected and add TextBox controls
for (int x = 0; x <= i; x++)
{
TextBox txtB = new TextBox();
txtB.ID = "Text" + x.ToString();
txtB.Text = "Text" + x.ToString();
PlaceHolder1.Controls.Add(txtB);
PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));
}
}

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:27 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


23
The PlaceHolder control, as well as the Panel control, exposes a Controls prop-
erty that refers to a collection of controls. We can manipulate the controls through that
collection. The power of dynamic control creation comes into its own when we build
data-driven applications that have widely varying needs for each form, and we want to
minimize code duplication and maximize object reuse. The final application is seen in
the following illustration, where three controls are selected.

PART III
Summary
In this chapter, you have seen a number of techniques used to present controls to the user,
ranging from the HTML control through server controls and user controls to custom
controls. The important thing is knowing the different control families and how to
properly add them to an application. Dynamic control creation will also assist you in
building powerful applications, and Microsoft always asks some questions on how the
dynamic creation is performed.
Now you are ready to learn how to make an application responsive and to make the
user interface usable by many different groups of users. That’s in the next chapter.

Test Questions
1. What HTML element is the asp:Label control rendered as when the target is
Internet Explorer?
A. <label>
B. <span>

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:27 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


24
C. <div>
D. <table>
2. What HTML element is the asp:Label control rendered as when the target is
Netscape Communicator?
A. <label>
B. <span>
C. <div>
D. <table>
3. What is the result when a Web Form containing the following line is compiled
and executed?
<asp:Button id="theButton" onClick="theEvent" />
A. The button control is created; theEvent is the Click event handler.
B. Compiler error; the control must be set to runat="server".
C. Compiler error; onClick is not a valid attribute.
D. Runtime exception; the control must be set to runat="server".
4. What HTML element is the asp:panel control rendered as?
A. <span>
B. <table>
C. <div>
D. <p>
5. How do you specify the parameters for the ads in the AdRotator control?
A. By programmatically setting the properties.
B. By using an initialization file in .xml format.
C. By using an initialization file in .txt format.
D. By using an initialization file in .ini format.
6. What of the following best describes a user control?
A. A collection of server controls gathered in a web file with the
<%@ Control %> directive.
B. A collection of controls that are compiled into an assembly.
C. A control that is built from multiple user-defined COM-based controls.
D. A simple lightweight control that can display text only.
7. Which of the following is valid after adding the following directive to
a Web Form?
<%@ Register TagPrefix="WWW" TagName"WWWControl" Src="WWWControl1.ascx" %>
A. <WWW:WWWControl1 id="theControl" runat="server" />

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:27 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
14

Chapter 14: Server Controls in ASP.NET


25
B. <asp:WWWControl id="theControl" runat="server" />
C. <WWW:WWWControl id="WWWContr" runat="server" />
D. <asp:WWWControl1 id="WWWContr" runat="server" />
8. You have correctly added the <%@ Register %> directive and the user-control
definition in the <asp:Form> tag, but when you run the application it fails.
What is the most likely cause of the failure?
A. The protected class variable for the control is missing from the codebehind
module.
B. The event registration is not performed; you must manually add it to the
InitializeComponent event handler.
C. There must be a call to the control’s constructor in the Page_load()

PART III
method.
D. The control must be added to the Web Form’s Controls collection.
9. After building a custom control, you test it by adding an ASP.NET web application
to the solution. You add a correct <%@ Register %> directive and a proper
declaration of the control in the <asp:Form> tag to the Web Form, but when
you execute the application you get an error. What is the most likely reason for
the problem?
A. The custom control must be compiled first.
B. The web application must have a reference to the control.
C. The custom control must be registered with Windows first.
D. The assembly from the custom control is not in the application’s bin
directory.
10. You have successfully created a custom control and a web application project to
test the control. The application runs with no problems, but when you look at
the Design view of the Web Form, the control is displayed using an error display.
What is the most efficient way to resolve the error display?
A. Move the control to the web application’s bin directory, and recompile the
application.
B. Add a reference to the control to the web application.
C. Change the Bindable attribute for the Default property in the control
to have a value of True.
D. Manually enter the 128-bit GUID for the control in the application’s
configuration file.
11. What method must be overridden in a custom control?
A. The Paint() method.
B. The Control_Build() method.

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:27 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
14

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide


26
C. The Render() method.
D. The default constructor.
12. Your manager has asked you if ASP.NET can be used with dynamic control
creation, and if it requires any extra software to make dynamic controls possible.
What would you answer your manager?
A. Yes, dynamic controls are possible using the standard control containers
from ASP.NET.
B. No, dynamic controls are not possible in ASP.NET.
C. Yes, dynamic controls are possible in ASP.NET using a third-party assembly.
D. Yes, dynamic controls are possible in ASP.NET by using the Web Services.

Test Answers
1. B.
2. B.
3. D.
4. C.
5. B.
6. A.
7. C.
8. A.
9. D.
10. B.
11. C.
12. A.

P:\010Comp\All-in-1\443-6\ch14.vp
Friday, August 23, 2002 4:59:27 PM

Das könnte Ihnen auch gefallen