Beruflich Dokumente
Kultur Dokumente
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.
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
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
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:
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
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
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
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:
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:
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:
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
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:
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
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.
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
the project name (Rotator) in the Project Explorer, and select Add | New Folder
from the context menu, as shown in Figure 14-5.
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
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
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
PART III
Figure 14-7 Setting the TargetSchema property
When the file is completed, it should look like the following code:
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
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
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:
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:
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
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.
In the preceding code segment, the reference to the user control sets the control’s ID
to 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
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
}
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:
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
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.
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
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:
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
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
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
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:
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:
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:
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
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
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:
// 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
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
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
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
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