Web Controls

 

Web controls are defined in the System.Web.UI.WebControls namespace and represent an alternative approach to HTML server controls. Like HTML controls, Web controls are server-side components that spring to life thanks to the runat="server" attribute. Unlike HTML controls, Web controls provide a programming interface that refactors the classic set of HTML attributes and events. For this reason, Web controls sometimes appear to be more consistent and abstract in the API design and richer in functionality, but they still generate valid markup. When hosted in .aspx pages, Web controls are characterized by the asp namespace prefix.

To a large degree, Web controls and HTML controls overlap and generate almost the same markup, although they do it through different programming interfaces. For example, the Web controls namespace defines the TextBox control and makes it available through the <asp:text-box> tag; similarly, the HTML controls namespace provides the HtmlInputText control and declares it using the <input> tag. Using either is mostly a matter of preference; only in a few cases will you run into slight functionality differences.

Generalities of Web Controls

The WebControl class is the base class from which all Web controls inherit. WebControl inherits from Control. The class defines several properties and methods that are shared, but not necessarily implemented, by derived controls. Most properties and methods are related to the look and feel of the controls (font, style, colors, CSS) and are subject to browser and HTML versions. For example, although all Web controls provide the ability to define a border, not all underlying HTML tags actually support a border.

Properties of Web Controls

Table 4-8 lists the properties available on the WebControl class.

Table 4-8: Specific Properties of Web Controls

Property

Description

AccessKey

Gets or sets the letter to press (together with Alt) to quickly set focus to the control in a Web form. Supported on Internet Explorer 4.0 and newer.

Attributes

Gets the collection of attributes that do not correspond to properties on the control. Attributes set in this way will be rendered as HTML attributes in the resulting page.

BackColor

Gets or sets the background color of the Web control.

BorderColor

Gets or sets the border color of the Web control.

BorderStyle

Gets or sets the border style of the Web control.

BorderWidth

Gets or sets the border width of the Web control.

ControlStyle

Gets the style of the Web server control. The style is an object of type Style.

ControlStyleCreated

Gets a value that indicates whether a Style object has been created for the ControlStyle property.

CssClass

Get or sets the name of the cascading style sheet (CSS) class associated with the client.

Enabled

Gets or sets whether the control is enabled.

Font

Gets the font properties associated with the Web control.

ForeColor

Gets or sets the foreground color of the Web control mostly used to draw text.

Height

Gets or sets the height of the control. The height is expressed as a member of type Unit.

Style

Gets a CssStyleCollection collection object made of all the attributes assigned to the outer tag of the Web control.

TabIndex

Gets or sets the tab index of the control.

ToolTip

Gets or sets the text displayed when the mouse pointer hovers over the control.

Width

Gets or sets the width of the control. The width is expressed as a member of type Unit.

The ControlStyle and ControlStyleCreated properties are used primarily by control developers, while the Style property is what application developers would typically use to set CSS attributes on the outer tag of the control. The Style property is implemented using an instance of the class CssStyleCollection. The CssStyleCollection class is a simple collection of strings like those you would assign to the HTML style attribute.

Styling Web Controls

The ControlStyle property evaluates to an object of type Style a class that encapsulates the appearance properties of the control. The Style class groups together some of the properties shown in Table 4-8, and it works as the repository of the graphical and cosmetic attributes that characterize all Web controls. The grouped properties are: BackColor, BorderColor, Border-Style, BorderWidth, CssClass, Font, ForeColor, Height, and Width. All properties of the Style class are strongly typed. The properties just mentioned are not persisted to the view state individually, but benefit from the serialization machinery supported by the Style object.

It should be clear by now that the Style class is quite different from the Style property, whose type is CssStyleCollection. Note that style values set through the Style property are not automatically reflected by the (strongly typed) values in the Style object. For example, you can set the CSS border-style through the Style property, but that value won't be reflected by the value of the BorderStyle property:

// Set the border color through a CSS attribute MyControl.Style["border-color"] = "blue"; // Set the border color through an ASP.NET style property MyControl.BorderColor = Color.Red; 

So what happens if you run the preceding code snippet? Which setting would win? When a control is going to render, the contents of both ControlStyle and Style properties are rendered to HTML style attributes. The ControlStyle property is processed first, so in case of overlapping settings the value stuffed in Style, which is processed later, would win, as shown by the following markup:

style="border-color:Red;border-color:blue;  " 

Managing the Style of Web Controls

The style properties of a Web control can be programmatically manipulated to some extent. For example, in the Style class, you can count on a CopyFrom method to duplicate the object and on the MergeStyle method to combine two style objects:

currentStyle.MergeStyle(newStyle); 

The MergeStyle method joins the properties of both objects. In doing so, it does not replace any property that is already set in the base object but limits itself to defining uninitialized properties. Finally, the Reset method clears all current attributes in the various properties of the style object.

Methods of Web Controls

The WebControl class supports a few additional methods that are not part of the base Control class. These methods are listed in Table 4-9.

Table 4-9: Specific Methods of Web Controls

Method

Description

ApplyStyle

Copies any nonempty elements of the specified style object to the control. Existing style properties are overwritten.

CopyBaseAttributes

Imports from the specified Web control the properties AccessKey, Enabled, ToolTip, TabIndex, and Attributes. Basically, it copies all the properties not encapsulated in the Style object.

MergeStyle

Like ApplyStyle, copies any nonempty elements of the specified style to the control. Existing style properties are not overwritten, though.

RenderBeginTag

Renders the HTML opening tag of the control into the specified writer. The method is called right before the control's RenderControl method.

RenderEndTag

Renders the HTML closing tag of the control into the specified writer. The method is called right after the control's RenderControl method.

All these methods are rarely of interest to application developers. They are mostly designed to support control developers.

Core Web Controls

The set of Web controls can be divided into various categories according to the provided functionality input and button controls, validators, data-bound controls, security-related controls, grid and view controls, plus a few miscellaneous controls that provide ad hoc functions and are as common on the Web as they are hard to catalogue (for example, calendar, ad rotator, and so forth).

In this chapter, we're focused on covering the most common and essential Web controls, such as the controls for capturing and validating the user's input and posting data to the server. We'll cover the various types of data-bound controls in Chapter 9, Chapter 10, and Chapter 11. Security-related controls, on the other hand, are slated for Chapter 15. Table 4-10 details the core server controls of ASP.NET.

Table 4-10: Core Web Controls

Control

Description

Button

Implements a push button through the <input> tag.

CheckBox

Implements a check box through the <input> tag.

FileUpload

Allows users to select a file to upload to the server. Not available in ASP.NET 1.x.

HiddenField

Implements a hidden field. Not available in ASP.NET 1.x.

HyperLink

Implements an anchor <a> tag, and lets you specify either the location to jump to or the script code to execute.

Image

Implements a picture box through the <img> tag.

ImageButton

Displays an image and responds to mouse clicks on the image like a real button.

ImageMap

Displays an image and optionally defines clickable hot spots on it. Not available in ASP.NET 1.x.

Label

Represents a static, nonclickable piece of text. Implemented through the <span> tag.

LinkButton

Implements an anchor <a> tag that uses only the ASP.NET postback mechanism to post back. It is a special type of hyperlink where the programmer can't directly set the target URL.

MultiView

Represents a control that acts as a container for a group of child View controls. Not available in ASP.NET 1.x.

Panel

Implements an HTML container using the <div> block element. In ASP.NET 2.0, the container supports scrolling. Note that in down-level browsers the control renders out as a <table>.

RadioButton

Implements a single radio button through the <input> tag.

Table

Implements the outer table container. Equivalent to the HTML <table> element.

TableCell

A table cell; is equivalent to the HTML <td> element.

TableRow

A table row; is equivalent to the HTML <tr> element.

TextBox

Implements a text box using the <input> or <textarea> tag as appropriate and according to the requested text mode. Can work in single-line, multiline, or password mode.

View

Acts as a container for a group of controls. A View control must always be contained within a MultiView control. Not available in ASP.NET 1.x.

Most controls in Table 4-10 look like HTML controls. Compared to HTML controls, their programming model is certainly richer and more abstract, but in the end it still generates valid and legal markup. If a given feature can't be obtained with raw HTML, there's no way a custom Web control can provide it. No matter how complex the programming model is, all Web controls must produce valid HTML for both up-level and down-level browsers.

Button Controls

In ASP.NET 2.0, controls that provide button functions are characterized by a new interface IButtonControl. Core controls that implement the interface are Button, ImageButton, and Link-Button. In general, by implementing IButtonControl any custom control can act like a button on a form.

The IButtonControl interface is a clear example of the refactoring process that the entire ASP.NET Framework went through in the transition from 1.x to 2.0. The interface now groups a few properties that most button controls (including some HTML button controls) support since ASP.NET 1.x. In addition to this, a few new properties heralding new functions have been added, such as PostBackUrl and ValidationGroup. Table 4-11 details the IButtonControl interface.

Table 4-11: The IButtonControl Interface

Name

Description

CausesValidation

Boolean value, indicates whether validation is performed when the control is clicked.

CommandArgument

Gets or sets an optional parameter passed to the button's Command event along with the associated CommandName.

CommandName

Gets or sets the command name associated with the button that is passed to the Command event.

PostBackUrl

Indicates the URL that will handle the postback triggered through the button control. This ASP.NET 2.0-specific feature is known as cross-page postback. (We'll cover this further in Chapter 5.)

Text

Gets or sets the caption of the button.

ValidationGroup

Gets or sets the name of the validation group that the button belongs to.

Visible

Boolean value, indicates whether the button control is rendered.

In addition to the properties defined by the IButtonControl interface, the Button class features two new properties in ASP.NET 2.0-OnClientClick and UseSubmitBehavior. The former standardizes a common practice that many developers used countless times in ASP.NET 1.x projects. OnClientClick lets you define the name of the JavaScript function to run when the client-side onclick event is fired. The following two statements are perfectly legal and equivalent:

// New in ASP.NET 2.0 Button1.OnClientClick = "ShowMessage()"; // Equivalent in ASP.NET 1.x Button1.Attributes["onclick"] = "ShowMessage()"; 

The OnClientClick property is available also on LinkButton and ImageButton controls.

By default, the Button class is rendered through a <input type=submit> tag. In this way, it takes advantage of the browser's submit mechanism to post back. The UseSubmitBehavior property allows you to change the default behavior. Set the UseSubmitBehavior property to false and the control will render out through an <input type=button> tag. Also in this case, though, the Button control remains a postback button. When UseSubmitBehavior is false, the control's onclick client event handler is bound to a piece of JavaScript code (the __doPostBack function) that provides the ASP.NET postback mechanism just like for LinkButton or ImageButton controls.

Important 

Buttons are not the only controls that can trigger a postback. Text boxes and check boxes (plus a few more data-bound list controls, which we'll see in Chapter 9) can also start a postback if their AutoPostBack property is set to true. (Note that the default setting is false.) When this happens, the control wires up to a client-side event onchange for text boxes and onclick for check boxes and initiates a postback operation via script.

HyperLinks

The HyperLink control creates a link to another Web page and is typically displayed through the text stored in the Text property. Alternatively, the hyperlink can be displayed as an image; in this case, the URL of the image is stored in the ImageUrl property. Note that if both the Text and ImageUrl properties are set, the ImageUrl property takes precedence. In this case, the content of the Text property is displayed as a ToolTip when the mouse hovers over the control's area.

The NavigateUrl property indicates the URL the hyperlink is pointing to. The Target property is the name of the window or frame that will contain the output of the target URL.

Images and Image Buttons

The Image control displays an image on the Web page. The path to the image is set through the ImageUrl property. Image URLs can be either relative or absolute, with most programmers showing a clear preference for relative URLs because they make a Web site inherently easier to move. You can also specify alternate text to display when the image is not available or when the browser doesn't render the image for some reason. The property to use in this case is AlternateText. The image alignment with respect to other elements on the page is set by using the ImageAlign property. Feasible values are taken from the homonymous enum type.

The Image control is not a clickable component and is simply limited to displaying an image. If you need to capture mouse clicks on the image, use the ImageButton control instead. The ImageButton class descends from Image and extends it with a couple of events Click and Command that are raised when the control is clicked. The OnClick event handler provides you with an ImageClickEventArgs data structure that contains information about the coordinates for the location at which the image is clicked.

The OnCommand event handler makes the ImageButton control behave like a command button. A command button has an associated name that you can control through the CommandName property. If you have multiple ImageButton controls on the same page, the command name allows you to distinguish which one is actually clicked. The CommandArgument property can be used to pass additional information about the command and the control.

Another new entry in ASP.NET 2.0 is the ImageMap control. In its simplest and most commonly used form, the control displays an image on a page. However, when a hot-spot region defined within the control is clicked, the control either generates a post back to the server or navigates to a specified URL. The hot spot is a clickable region within the displayed image. The hot spot is implemented with a class that inherits from the HotSpot class. There are three predefined types of hot spots polygons, circles, and rectangles.

Check Boxes and Radio Buttons

Check boxes and radio buttons are implemented through the <input> tag and the type attribute set to checkbox or radio. Unlike the HTML control versions, the Web control versions of check boxes and radio buttons let you specify the associated text as a property. The HTML elements and corresponding HTML controls lack an attribute whose content becomes the text near the check box or radio button. In HTML, to make the text near the check box or radio button clickable, you have to resort to the <label> tag with the for attribute:

<input type="checkbox"  /> <label for="ctl">Check me</label> 

Neither the HtmlInputCheckBox nor the HtmlInputRadioButton control adds a label; this is your responsibility. The counterparts to these Web controls, on the other hand, are not bound to the HTML syntax and do precisely that they automatically add a Text property, which results in an appropriate <label> tag. For example, consider the following ASP.NET code:

<asp:checkbox runat="server"  text="Check me" /> 

It results in the following HTML code:

<input type="checkbox"  /> <label for="ctl">Check me</label> 

Scrollable Panels

The Panel control groups controls in a <div> tag. It allows developers to add and remove controls, and it supports style information. In ASP.NET 2.0, panels support horizontal and vertical scrollbars implemented through the overflow CSS style. Here's an example that demonstrates a scrollable panel:

<asp:Panel  runat="server" Height="80px" Width="420px"            ScrollBars="Auto" BorderStyle="Solid">     <h2>Choose a technology</h2>     <asp:CheckBox  runat="server" Text="ASP.NET" /><br />     <asp:CheckBox  runat="server" Text="ADO.NET" /><br />     <asp:CheckBox  runat="server" Text="Web Services" /><br />     <asp:CheckBox  runat="server" Text="XML" /><br />     <asp:CheckBox  runat="server" Text="SQL Server" /><br />     <asp:CheckBox  runat="server" Text="CLR" /><br /> </asp:Panel> 

Figure 4-4 shows the page in action.

image from book
Figure 4-4: A page that uses a scrollable panel.

Text Controls

The fastest way to insert text in a Web page is through literals that is, static text inserted directly in the .aspx source. This text will still be compiled to a control, but at least the number of dynamically created literal controls will be the minimum possible because any sequence of consecutive characters will be grouped into a single literal. If you need to identify and manipulate particular strings of text programmatically, you can resort to a Literal control or, better yet, to the richer Label control. Modifiable text requires a TextBox.

Some minor changes occurred to these controls in ASP.NET 2.0. First, a few new interfaces have been introduced to logically group capabilities. They are ITextControl and IEditableTextControl. The former includes the sole Text property and is implemented by Literal, Label, TextBox, and list controls. The latter interface defines the TextChanged event and is specific to TextBox and list controls.

It is worth mentioning a new accessibility feature of the Label control the AssociatedControlID property. The property takes the ID of a control in the page typically, an input control such as a TextBox that you want to associate with the label. The AssociatedControlID changes the way the Label control renders out. It is a <span> tag if no associated control is specified; it is a <label> tag otherwise. Let's consider the following example:

<asp:Label  runat="server" Text="Sample text" /> <asp:TextBox  runat="server" /> 

As is, it generates the following markup:

<span >Sample text</span> <input name="TextBox1" type="text"  /> 

If you set the label's AssociatedControlID property to TextBox1, the markup changes as shown here:

<label for="TextBox1" >Sample text</label> <input name="TextBox1" type="text"  /> 

The run-time behavior changes a bit because now any click on the label text will be extended to the associated control. For example, clicking on the label will move the input focus to a text box, or it will select or deselect a check box.

Note 

AssociatedControlID is a feature designed to improve the accessibility of the resulting page. In Visual Studio .NET 2005, you can check any page for accessibility rules (both WCAG and Section 508) by clicking on the Tools|Check Accessibility menu item.

Hidden Fields and File Upload

If you're looking for a more comfortable programming interface to create hidden fields and upload files, two new Web controls in ASP.NET 2.0 might help. The HiddenField and FileUpload controls add no new functionality to the ASP.NET programmer's bag, but they have been added to the toolbox for completeness. A hidden field can be created in two other ways that work with ASP.NET 1.x, too. For example, you can use the RegisterHiddenField method on the Page class:

// Works in ASP.NET 1.x but declared obsolete in ASP.NET 2.0 RegisterHiddenField("HiddenField1", "Great book!"); 

Note that the RegisterHiddenField method has been flagged as obsolete in ASP.NET 2.0. The recommended code analogous to the previous snippet is shown next:

// Recommended code in ASP.NET 2.0 ClientScriptManager.RegisterHiddenField("HiddenField1", "Great book!"); 

In addition, to create a hidden field you can resort to the HTML markup, adding a runat attribute if you need to set the value programmatically:

<input runat="server"  type="hidden" value=" " /> 

Analogous considerations can be made for the FileUpload control, which provides the same capabilities as the HtmlInputFile control that we discussed earlier. In this case, though, the programming interface is slightly different and perhaps more intuitive. The HasFile property and SaveAs method hide any reference to the object that represents the posted file. Likewise, the FileName property provides a more immediate name for the name of the posted file. The code to upload a file can be rewritten as follows:

if (FileUpload1.HasFile) {      // Get the name of the file to upload.      string fileName = FileUpload1.FileName;     string targetPath = GetSavePath(fileName);      FileUpload1.SaveAs(targetPath); } 

Whether you use FileUpload or HtmlInputFile is mostly a matter of preference.

Creating Tables

As you might have noticed, there are three ways to build tables in ASP.NET pages: static HTML tags, HtmlTable controls, and Table controls. Which is the best option?

Static HTML tags provide the greatest flexibility as far as the structure of the table is concerned. If you want to support all possible tags that the HTML specification allows, this is the option to take. By contrast, HtmlTable appears to be the least flexible option. In fact, it accepts only row tags and silently removes any additional and unsupported tags.

The Table control in ASP.NET 2.0 supports various row types (normal, header, footer) and dynamic manipulation of rows and cells, but it still lacks full declarative support of all possible HTML table-related tags and attributes, including COLGROUP and TBODY. Note, though, that each table row can be associated with a table section (body, footer, header) programmatically. This is possible through the TableSection property of the TableRow class.

Miscellaneous Web Controls

The WebControls namespace also includes a few controls that provide useful functionality that is common in Web applications. In particular, we'll examine the AdRotator control, which works like an advertisement banner, and the Calendar control, which is a flexible and highly interactive control used to specify a date.

The AdRotator Control

Abstractly speaking, the AdRotator control displays an automatically sized image button and updates both the image and the URL each time the page refreshes. The image to display and other information is read from an XML file written according to a specific schema. More concretely, you use the AdRotator control to create an advertisement banner on a Web Forms page. The control actually inserts an image and a hyperlink in the page and makes them point to the advertisement page selected. The image is sized by the browser to the dimensions of the AdRotator control, regardless of its actual size. The following code shows a typical XML advertisement file:

<Advertisements> <Ad>     <ImageUrl>6235.gif</ImageUrl>     <NavigateUrl>www.microsoft.com/MSPress/books/6235.asp</NavigateUrl>     <AlternateText>Applied XML Programming with .NET</AlternateText>     <Impressions>50</Impressions> </Ad> <Ad>     <ImageUrl>5727.gif</ImageUrl>     <NavigateUrl>www.microsoft.com/MSPress/books/5727.asp</NavigateUrl>     <AlternateText>Building Web Solutions with ASP.NET</AlternateText>     <Impressions>50</Impressions> </Ad> </Advertisements> 

The <Advertisement> root node contains multiple <Ad> elements, one per each image to show. The advertisement file must reside in the same application as the AdRotator control. The syntax of the AdRotator control is as follows:

<%@ Page Language="C#" %> <html> <head><title>Pro ASP.NET (Ch04)</title></head> <body>     <form runat="server">         <h1>Dino Esposito's Books</h1>         <asp:AdRotator runat="server"              AdvertisementFile="MyBooks.xml" />     </form> </body> </html> 

In the XML advertisement file, you use the <ImageUrl> node to indicate the image to load and the <NavigateUrl> node to specify where to go in case of a click. The <AlternateText> node indicates the alternate text to use if the image is unavailable, whereas <Impressions> indicates how often an image should be displayed in relation to other images in the advertisement file. Each image can also be associated with a keyword through the <Keyword> node. Of all the elements, only <ImageUrl> is required.

Once per roundtrip, the AdRotator control fires the server-side AdCreated event. The event occurs before the page is rendered. The event handler receives an argument of type AdCreatedEventArgs, which contains information about the image, navigation URL, alternate text, and any custom properties associated with the advertisement. The AdCreated event can be used to select programmatically the image to show. The XML schema of the advertisement is not fixed and can be extended with custom elements. All nonstandard elements associated with the selected advertisement will be passed to the AdCreated event handler stuffed in the AdProperties dictionary member of the AdCreatedEventArgs class.

Note 

The AdRotator control has undergone a significant change in ASP.NET 2.0. It is derived from WebControl in ASP.NET 1.x, but it inherits from DataBoundControl in ASP.NET 2.0. Among other things, this means that the advertisement feed can also be provided through an XML or a relational data source. Image and navigation URLs, as well as the alternate text, can be read from fields belonging to the data source. The control cannot be bound to more than one data source at a time. If more than one property AdvertisementFile, DataSourceID, or DataSource is set, an exception will be thrown.

The Calendar Control

The Calendar control (shown in Figure 4-5) displays a one-month calendar and allows you to choose dates and navigate backward and forward through the months of the year. The control is highly customizable both for appearance and functionality. For example, by setting the SelectionMode property, you can decide what the user can select that is, whether a single date, week, or month can be selected:

<asp:calendar runat="server"      SelectedDate="2005-05-04" VisibleDate="2005-05-04" /> 

image from book
Figure 4-5: The Calendar control in action.

The VisibleDate property sets a date that must be visible in the calendar, while SelectedDate sets with a different style the date that is rendered as selected. The control also fires three ad hoc events: DayRender, SelectionChanged, and VisibleMonthChanged. The DayRender event signals that the control has just created a new day cell. You can hook the event if you think you need to customize the cell output. The SelectionChanged event fires when the selected date changes, while VisibleMonthChanged is raised whenever the user moves to another month using the control's selector buttons.

The Calendar control originates a roundtrip for each selection you make. Although it is cool and powerful on its own, for better performance you might also want to provide a plain text box for manually typing dates.

The Xml Control

The Xml control, defined by the <asp:Xml> tag, is used to output the content of an XML document directly into an ASP.NET page. The control can display the source XML as is or as the result of an XSL transformation (XSLT). The Xml control is a sort of declarative counterpart for the XslTransform class and can make use of the .NET Framework XSLT transform class internally.

You use the Xml control when you need to embed XML documents in a Web page. For example, the control is extremely handy when you need to create XML data islands for the client to consume. The control lets you specify a document to work with and, optionally, a transformation to apply. The XML document can be specified in a variety of formats an XML document object model, string, or file name. The XSLT transformation can be defined through either an already configured instance of the .NET Framework XslTransform class or a file name:

<asp:xml runat="server"     documentsource="document.xml"     transformsource="transform.xsl" /> 

If you're going to apply some transformation to the XML data, you could also embed it inline between the opening and closing tags of the control. The control also makes it easier to accomplish a common ASP task: apply browser-dependent transformations to portions of the page expressed in an XML meta language. In this case, you exploit the programming interface of the control as follows:

<asp:xml runat="server"  documentsource="document.xml" /> 

In the Page_Load event, you just check the browser capabilities and decide which transformation should be applied:

void Page_Load(object sender, EventArgs e) {     if (IsInternetExplorer(Request.Browser))         theXml.TransformSource = "ie5.xsl";     else         theXml.TransformSource = "downlevel.xsl"; } 

The PlaceHolder Control

The PlaceHolder control is one of the few controls in the WebControls namespace that isn't derived from the WebControl class. It inherits from Control and is used only as a container for other controls in the page. The PlaceHolder control does not produce visible output of its own and is limited to containing child controls dynamically added through the Controls collection. The following code shows how to embed a placeholder control in a Web page:

<asp:placeholder runat="server"  /> 

Once you have a placeholder, you can add controls to it. As mentioned, the placeholder does not add extra functionality, but it provides for grouping and easy and direct identification of a group of related controls. The following code demonstrates how to create a new button and add it to an existing placeholder:

Button btn = new Button(); btn.Text = "Click me"; theToolbar.Controls.Add(btn); 

The PlaceHolder control reserves a location in the control tree and can be extremely helpful in identifying specific areas of the page to customize and extend by adding controls programmatically.

Important 

Note that each control dynamically added to the Controls collection of a parent control is not restored on postback. If the control generates some input elements on the client, the client data is regularly posted but there will be no server-side control to handle that. To avoid this, you must remember that you created a certain control dynamically and re-create it while the page loads on postbacks. To remember that a certain control was added to a parent, you can create a custom entry in the view state or use a hidden field.

View Controls

ASP.NET 2.0 introduces two new related controls to create a group of interchangeable panels of child controls. The MultiView control defines a group of views, each represented with an instance of the View class. Only one view is active at a time and rendered to the client. The View control can't be used as a standalone component and can only be placed inside a MultiView control. Here's an example:

<asp:MultiView runat="server" >     <asp:View runat="server" >         ...     </asp:View>     <asp:View runat="server" >         ...     </asp:View>     <asp:View runat="server" >         ...     </asp:View> </asp:MultiView> 

You change the active view through postback events when the user clicks buttons or links embedded in the current view. To indicate the new view, you can either set the ActiveViewIndex property or pass the view object to the SetActiveView method.

Figure 4-6 shows a sample page in action. You select the page from the drop-down list and refresh the view:

void Page_Load(object sender, EventArgs e) {     // Views is an auto-postback drop-down list     Tables.ActiveViewIndex = Views.SelectedIndex; } 

image from book
Figure 4-6: A MultiView control in action.

The combination of View and MultiView controls lends itself very well to implementing wizards. In fact, the new ASP.NET Wizard control uses a MultiView control internally. We'll cover the Wizard control in Chapter 6.

 


Programming Microsoft ASP. Net 2.0 Core Reference
Programming Microsoft ASP.NET 2.0 Core Reference
ISBN: 0735621764
EAN: 2147483647
Year: 2004
Pages: 112
Authors: Dino Esposito
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net