14 - server controls in asp

Upload: irina-elena

Post on 07-Apr-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/4/2019 14 - Server Controls in ASP

    1/27

    THIS PAGE INTENTIONALLY LEFT BLANK

  • 8/4/2019 14 - Server Controls in ASP

    2/27

    CHAPTER

    14Server Controlsin ASP.NETIn 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 canstart 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 simplifythe processing of data and centralize the functionality for a group of controls.

    Working with ASP ControlsThe building blocks of our Web Forms are the controls that give us the ability to displaydata to the user, as well as enabling the user to interact with the application. There are acouple 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 theserver, and there are the intrinsic HTML controls that use a server control to encapsulatethe 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 validatethe data from the user, and we looked at the use of these controls in Chapter 12. Whatthis section will add to the control pallet is the use of the so-called rich controls. These arecontrols with no direct HTML counterpartthey are combinations of different intrinsiccontrols 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

    1

  • 8/4/2019 14 - Server Controls in ASP

    3/27

    have to produce a least common denominator version of your site or have multipleversions for different browsers. For example, we do not have to produce one version ofour web site for each browser on the market; ASP.NET provides support to generateHTML that is browser specific taking care not to send HTML elements that are notsupported 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 bothNetscape and Internet Explorer, while the Calendar control would be rendered totallydifferent between the different browsers.

    Your Web Forms can be configured to meet a lowest-common-denominatorbrowser by changing the setting for TargetSchema on the document object, asshown 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 propertybased on the expected client baseif the site will be used on the Internet, you could setit to a version 4 browser; for an intranet you could set a very specific, high-versionbrowser.

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

    2

    Figure 14-1

    Changing the

    TargetSchema

    for theWeb Form

  • 8/4/2019 14 - Server Controls in ASP

    4/27

    Base Properties of Server ControlsAll the server controls have a common set of base properties, in addition to their specificproperties. 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 Frameworkwill render the control based on the target browser, ensuring that the page will lookokay in any browser.

    The followingLabel control uses some of the properties for the control:

    Hello World!

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

    Hello World!

    Chapter 14: Server Controls in ASP.NET

    3

    Description

    BackColor Sets the background color of the control. This property can be set to any ofthe color constants in the .NET Frameworks Color structure property,such as DodgerBlue, AntiqueWhite, or to hexadecimal literal values like#C8C8C8 (gray).

    BorderWidth Sets the width of the controls border, in pixels.

    Enabled Determines whether or not the control is available for user interaction. If thisproperty is set to False, the control will be grayed out and the control will notprocess any event until the Enabled property has been set to True.

    Font Controls the appearance of the text in the control. This property has anumber 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 toTrue 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 themouse 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 thembased on the users selections.

    Width Sets the width of the control.

    Table 14-1 The Most Commonly Used Base Properties for Server Controls

  • 8/4/2019 14 - Server Controls in ASP

    5/27

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

    4

    The HTMLrendered for the Netscapebrowser is tailoredforthat browsers specialabilities:

    Hello World!

    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

    users 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.

    HTMLEquivalent Description

    Button Button This is the common command button. It uses the Clickevent to communicate with the application.

    CheckBox Checkbox CheckBox is the control you will use for Yes or Noselections.

    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-onlyinformation.

    ListBox select This is a control that allows the user to select an itemin a list. The ListBox control can optionally allow multipleselections.

    Panel div The Panel gives us an area in the page that can be usedto 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 enterinformation on the web page. The control will be renderedas a text input control.

    Table 14-2 The Intrinsic Server Controls

  • 8/4/2019 14 - Server Controls in ASP

    6/27

    Chapter 14: Server Controls in ASP.NET

    5

    We covered event handling and registration in detail in Chapter 11, and well see itput 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 projectButton1 on thelocalhost server.

    After the project is created open the HTML view of the web page. We will use a servercontrol to insert an element in the HTML part of the Web Form file (.aspx) as wevedone for the Button control in the following line of HTML code:

    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 theInitializeComponent() method that will run when the Web Form is initially cre-ated, or by adding the attribute to the control when it is defined. The following codeline defines the event handler in the Button definition:

    The event handler for the Click event is defined asbuttonClick(). OnClick is thekeyword that tells ASP.NET that we are talking about the Click event.

    Expand the code display and locate the InitializeComponent() method. Thecode 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 lookat 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 thanwriting individual eventhandlers. In this next example we will use a number of differentcontrols to create a converter application that will convert from km/h to mph. We will

    work through the Visual Studio .NET IDE to buildan application named Panel1 onthelocalhost server. The user interface of the application is created as in Figure 14-2.

    To place all the controls, weusedthe following code for the HTMLportion of the form:

    WebForm1

    The speed converter

  • 8/4/2019 14 - Server Controls in ASP

    7/27

    mph

    km/h

    The bold code in the preceding listing shows how the Panel control encapsulates theother controls that are in the panel. Note that the spaces that are inserted are there to aidin 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 codebehindmodule 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 componentinto a div HTML element that will be displayed using the client browser.

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

    6

    Figure 14-2 The user interface of the speed converter

  • 8/4/2019 14 - Server Controls in ASP

    8/27

    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 ControlsThe 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 theirusage.

    These controls add functionality that is implemented by JavaScript client-side codeand standard HTML elements. As an example, we will look more closely at theAdRotator control, which displays images as an ad banner. The images can be of anyfile type that can be displayed in a browser, such as .gif, .jpg, and so on. The imagecan be clickable so the user will be taken to a predetermined site for each image. Whatimages are displayed and how they behave is determined by an XML document that iscreated 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 displayHello World messages in different languages each time the page is redisplayed. Forthis 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 calledimages in the root of the application. On our server, the folder is locatedatc:\inetpub\wwwroot\Rotator\images.

    To start the project, create a new application named Rotator on the localhostserver. 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 calledImages and add the five .gif files to the folder. To create the new folder, right-click on

    Chapter 14: Server Controls in ASP.NET

    7

    Figure 14-3

    The finished

    speed converter

  • 8/4/2019 14 - Server Controls in ASP

    9/27

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

    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 isredisplayed by the postback process.

    Calendar This control displays a one-month calendar that can be customized andused in any situation where a date display is needed.

    CheckBoxList This is a grouping ofCheckBox controls that forms a list, which can bedynamically created from databases. The list is programmaticallyaccessible through the ID of the list.

    ImageButton This control has a clickable image that may have coordinates for imagemap functionality.

    LinkButton This is a button displayed as a hyperlink.

    RadioButtonList This is a grouping ofRadioButton controls that will behave as mutuallyexclusive controls. The entire list is accessible through the ID of the list.

    Table 14-3 Rich Controls

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

  • 8/4/2019 14 - Server Controls in ASP

    10/27

    Now you can add the images to the new folder by either dragging them there from MyComputer, 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 finalresult should look something like what is shown in Figure 14-6.

    TheAdRotatorhas anAdvertisementFileproperty that determines theimages tobe displayed, as well as the text version of the image for those browsers that cannot (or willnot) display graphics. The format of the AdvertisementFile is based on the Ad Rotatortemplate.Table 14-4 enumerates theparameters fortheAdvertisementFileproperty.

    Our example is built around a web application that has five images calledad1.gif,ad2.gif,ad3.gif,ad4.gif, andad5.gif. The web pages that the images are referringto are created using the names HTMLPage1.htm, HTMLPage2.htm, HTMLPage3.htm,HTMLPage4.htm and HTMLPage5.htm (you can find the images and HTML pages inthe Chapter 14 folder on the CD).

    The AdvertisementFile is an XML document that we need to create for theAdRotator. 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 itRotator.xml.After the file is created, the XML Editor will open.

    Chapter 14: Server Controls in ASP.NET

    9

    Figure 14-5 Adding a folder to the project

  • 8/4/2019 14 - Server Controls in ASP

    11/27

    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 to the file.

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

    10

    Figure 14-6

    The Rotator

    project with theImages folder

    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 exceed2,048,000,000 1 (2,047,999,999). This is a technical limit.

    Table 14-4 The Parameters for the AdvertisementFile Property

  • 8/4/2019 14 - Server Controls in ASP

    12/27

    Chapter 14: Server Controls in ASP.NET

    11

    4. Add an element as a child element to the elementin XML file. The properties for each image are inserted in the element.

    5. To add the items from the Project Explorer, drag and drop the items into the

    XML editor. Drag the image into the node, as well as the HTML page thatcorresponds 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:

    Images/ad1.gif

    http://localhost/Rotator/HTMLPage1.htm

    The AD1.GIF

    Test10

    Figure 14-7 Setting the TargetSchema property

  • 8/4/2019 14 - Server Controls in ASP

    13/27

    Images/ad2.gif

    http://localhost/Rotator/HTMLPage2.htm

    The AD2.GIF

    Test

    10

    To add the XMLAdvertisementFile to theAdRotator control, browse for it byclicking on the ellipsis (three dots) next to the AdvertisementFile property, selectthe Rotator.xml file, and click OK.

    Save all the files, and then run the application by pressing the F5 key. Click thebrowsers refresh button and notice how the banner changes; click on the banner andnote that the browser displays the HTML page. The AdRotator control is rendered asan 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 ControlsWhen we need to use the same controls in many different forms, it becomes tricky tokeep 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 tobuild reusable controls that can be treated as components: user controls and customcontrols. User controls are scripted server controlsreally converted ASP.NET pages. Cus-tom controls are compiled into .NET assemblies that can be used wherever a control isneeded.

    We will start by looking at user controls; custom controls will be discussed later inthis section.

    Building and Using a User ControlA user control is a Web Form that has been converted into a reusable component thatcan 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 inall the Web Forms. First lets 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 anda TextBox to form one control. To create the user control, start a new project on thelocalhost server and call itUserTest. Once the project has been created, add the usercontrol by selecting Project | Add New Item. This displays the Add New Item dialog boxselect the Web User Control template, andcall the fileWUCUser.ascx, as shown here.

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

    12

  • 8/4/2019 14 - Server Controls in ASP

    14/27

    Chapter 14: Server Controls in ASP.NET

    13

    The files that are added to the project are similar to the files that make up a WebForm: there is the form file (.ascx) and the codebehind file (.ascx.cs). Youll needto add somecontrols 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 directive to theWebForm1.aspx file. The directive should look like this:

  • 8/4/2019 14 - Server Controls in ASP

    15/27

    The Register directive lets us specify how we will refer to the user control, and theTagPrefix and TagName are taken together to form the name of the element,, that we will use in the form to display the control.

    The HTML listing forWebForm1.aspx follows, with the additions in bold.

    WebForm1

    In the preceding code segment, the reference to the user control sets the controls IDto theUserControl:

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

    14

    Figure 14-8 TheWUCUser control

  • 8/4/2019 14 - Server Controls in ASP

    16/27

    In order to use the ID, we need a variable that is declared in the codebehind module forthe Web Form (WebForm1.aspx.cs). The following code segment shows the manualaddition we need to make toWebForm1.aspx.cs for the code to compile, with theaddition 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;

    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 theTextBox 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 SelectionChangedeventof the Calendar control so there will be feedbackwhen the date is changed in thecontrol.

    To add the event handler, double-click the Calendar control in theWUCUser.ascxfiles Design view. The final code in the codebehind file (WUCUser.ascx.cs) shouldlook 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();

    }

    Chapter 14: Server Controls in ASP.NET

    15

  • 8/4/2019 14 - Server Controls in ASP

    17/27

    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 essentiallyscripted ASP.NETforms 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 ControlCustom 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) andbe available to all applications on that server. Custom controls arebuilt-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) builtby using the drag and drop functionsof 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 directive to the top of the Web Form. The assembly thatcontains the custom control should be added to the bin directory in the root of the webapplication or to the GAC so that the application can find the assembly.

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

    16

  • 8/4/2019 14 - Server Controls in ASP

    18/27

    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 ofWCC, a Namespace ofWCCustomWebContols, and an Assembly name ofWCCustomWebControls:

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

    The next thing wehave to lookat is how to build these compiled customcontrols thatcan be reused betweenprojects. The example will take you through the building of a cus-tom control that acts as a text area. We will build the example usingVisual Studio .NET.

    Start by creating a custom control project from the Web Control Library template,and name itCusControl1. The project wizard builds a default control that you canstart your developments withthe project is runnable, but you need to provide thecode to use the control.

    As you work on the control, you will also need a way of testing it. There are a coupleof ways of doing this: you can create a second project that uses the control, or you couldadd a web application project to the custom control solution. In this example, we willuse 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 templateensure 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 youd have to copy the custom controls assemblyto the web applications bin directory every time you recompiled the custom control. Tomake the development easier, set the properties for the custom control project to sendthe 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 theproject (CusControl1) in the Solution Explorer of the custom control project.

    2. Expand the Configurations Properties folder and select the Build items to findthe Output Path.

    3. Set the Output Path to the location of the web applications bin directory. In

    our case that is c:\Inetpub\wwwroot\CustControlTest\bin. Make sureyou 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 intothe bin directory of the web application, which is the location wherethe application will

    Chapter 14: Server Controls in ASP.NET

    17

  • 8/4/2019 14 - Server Controls in ASP

    19/27

    search for assemblies. Setting the Configuration Properties to All Configurations meansthat 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 byright-clicking on the CustControlTest project and selecting Set as Startup Projectfrom the context menu.

    Now you can add the following two lines to the web applications HTML view. Theregistration of the Custom Control assembly and namespace makes the control avail-able to the web application:

    WebForm1

    The first highlighted line makes the custom control available to the application by regis-tering the TagPrefix, Namespace, and Assembly. The application will search forthe assemblies starting in the bin directory.

    Now we can run the application by pressingF5. The resultingdisplay 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

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

    18

  • 8/4/2019 14 - Server Controls in ASP

    20/27

    Chapter 14: Server Controls in ASP.NET

    19

    when you execute the application. The problem has to do with the application notknowing about the custom control at design time. It only looks for the assembly at runtime, so what we need to do isadd a reference to the control in our Web Form project.

    To do so, right-click on the References folder of the web application project. Underthe .NET tab, select browse, and select the assembly to be added as shown in the follow-

    ing illustration. ClickOpen and then OK to add the custom control to the project. Rerunthe application, and the error in the Design view should be gone and the control shouldbe visible instead. A second benefit that comes from adding the reference to the controlis that you can now use it in the codebehind module as well.

    Now that we have created and used a custom control, we will look a little closer atwhat the custom control is, and why this stock implementation that is supplied with Vi-sual Studio .NET is behaving like a Label control. Heres the codebehind module forthe custom control:

    using System;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.ComponentModel;

    namespace CusControl1

    {

    [DefaultProperty("Text"),

    ToolboxData("")]

    public class WebCustomControl1 : System.Web.UI.WebControls.WebControl

    {

    private string text;

  • 8/4/2019 14 - Server Controls in ASP

    21/27

    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 atthe first attribute:

    [DefaultProperty("Text"), ToolboxData("")]

    This specifies that the control will have a default property (Text) and it specifies the datafor 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 propertypage for the control, and the default value is an empty string. The last bold line in thissegment 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 Rendermethod as follows:

    protected override void Render(HtmlTextWriter output)

    {

    for (int x=Text.Length-1; x > 0; x--){

    output.Write(Text[x]);

    }

    }

  • 8/4/2019 14 - Server Controls in ASP

    22/27

    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 CreationThere will be many times when you do not knowhow many controls will be needed in aform. In instances where the user can select progressive disclosure (when the amount ofdata is increased based on the users request) designingdynamic control structures thatcan be added at run time is recommended. These dynamic controls must be added to acontainer control for them to be part of the Web Form; the container control will eitherbe 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 allowsus to add additional TextBox controls to a form, depending on the selection from aDropDownList control. To get started, create a new project on the localhost andcall itDynCntr. Then add a PlaceHolder control to the project, as well as a Labeland a DropDownList control. The layout of the final form is shown in next.

    Chapter 14: Server Controls in ASP.NET

    21

  • 8/4/2019 14 - Server Controls in ASP

    23/27

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

    WebForm1

    One

    Two

    ThreeFour

    Five

    Six

    Seven

    How many Controls?

    The bold sections in the preceding code were added after the controls were positionedusing the Design view.

    The dynamic behavior for the application comes from the SelectedIndexChangedevent 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

  • 8/4/2019 14 - Server Controls in ASP

    24/27

    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 thatcollection. The power of dynamic control creation comes into its own when we builddata-driven applications that have widely varying needs for each form, and we want tominimize code duplication and maximize object reuse. The final application is seen in

    the following illustration, where three controls are selected.

    SummaryIn this chapter, you haveseen a number of techniques used to present controls to the user,ranging from the HTML control through server controls and user controls to customcontrols. The important thing is knowing the different control families and how toproperly add them to an application. Dynamic control creation will also assist you inbuilding powerful applications, and Microsoft always asks some questions on how thedynamic creation is performed.

    Now you are ready to learn how to make an application responsive and to make theuser interface usable by many different groups of users. Thats in the next chapter.

    Test Questions

    1. What HTML element is the asp:Label control rendered as when the target isInternet Explorer?

    A.

    B.

    Chapter 14: Server Controls in ASP.NET

    23

  • 8/4/2019 14 - Server Controls in ASP

    25/27

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

    24

    C.

    D.

    2. What HTML element is the asp:Label control rendered as when the target isNetscape Communicator?

    A.

    B.

    C.

    D.

    3. What is the result when a Web Form containing the following line is compiledand executed?

    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.

    B.

    C.

    D.

    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 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 toa Web Form?

    A.

  • 8/4/2019 14 - Server Controls in ASP

    26/27

    B.

    C.

    D.

    8. You have correctly added the directive and the user-control

    definition in the 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 codebehindmodule.

    B. The event registration is not performed; you must manually add it to theInitializeComponent event handler.

    C. There must be a call to the controls constructor in the Page_load()method.

    D. The control must be added to the Web Forms Controls collection.

    9.

    After building a custom control, you test it by adding an ASP.NET web applicationto the solution. You add a correct directive and a properdeclaration of the control in the tag to the Web Form, but when

    you execute the application you get an error. What is the most likely reason forthe 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 applications bindirectory.

    10. You have successfully created a custom control and a web application project totest the control. The application runs with no problems, but when you look atthe 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 applications bin directory, and recompile theapplication.

    B. Add a reference to the control to the web application.

    C. Change the Bindable attribute for the Default property in the controlto have a value of True.

    D. Manually enter the 128-bit GUID for the control in the applicationsconfiguration file.

    11. What method must be overridden in a custom control?

    A. The Paint() method.

    B. The Control_Build() method.

    Chapter 14: Server Controls in ASP.NET

    25

  • 8/4/2019 14 - Server Controls in ASP

    27/27

    C. The Render() method.

    D. The default constructor.

    12. Your manager has asked you if ASP.NET can be used with dynamic controlcreation, 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 containersfrom 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.

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

    26