Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Pro ASP.NET 2.0 In CSharp 2005 (2005) [eng]

.pdf
Скачиваний:
92
Добавлен:
16.08.2013
Размер:
29.8 Mб
Скачать

108 C H A P T E R 4 S E R V E R C O N T R O L S

The HtmlContainerControl Class

Any HTML tag that has both an opening and a closing tag can contain other HTML content or controls. One example is the anchor tag, which usually wraps text or an image with the tags <a>…</a>. Many other HTML tags also work as containers, including everything from the <div> tag (which allows you to format a block of content) to the lowly <b> tag (which applies bold formatting). These tags don’t map to specific HTML server control classes, but you can still use them with the runat="server" attribute. In this case, you interact with them using the HtmlGenericControl class, which itself derives from HtmlContainerControl.

To support containment, the HtmlContainerControl class adds the two properties shown in Table 4-4.

Table 4-4. HtmlContainerControl Properties

Property

Description

InnerHtml

Returns or sets the HTML text inside the opening and closing tags. When you

 

use this property, all characters are left as is. This means you can embed HTML

 

markup (bolding text, adding line breaks, and so on).

InnerText

Returns or sets the text inside the opening and closing tags. When you use this

 

property, any characters that would be interpreted as special HTML syntax (such

 

as the <, the angle bracket) are automatically replaced with the HTML entity

 

equivalents.

 

 

The HtmlInputControl Class

The HTML input controls allow for user interaction. These include the familiar graphical widgets, including check boxes, text boxes, buttons, and list boxes. All of these controls are generated with the <input> tag. The type attribute indicates the type of input control, as in <input type="text"> (a text box), <input type="submit"> (a submit button), and <input type="file"> (controls for uploading a file).

Server-side input controls derive from HtmlInputControl, which adds the properties shown in Table 4-5.

Table 4-5. HtmlInputControl Properties

Property

Description

Name

Gets the unique identifier name for the HtmlInputControl.

Type

Gets the type of an HtmlInputControl. For example, if this property is set to text,

 

the HtmlInputControl is a text box for data entry.

Value

Gets or sets the value associated with an input control. The value associated with

 

a control depends on the type of control. For example, in a text box this property

 

contains the text entered in the control. For buttons, this defines the text on the

 

button.

 

 

The HTML Server Control Classes

Table 4-6 lists all the available HTML server controls and the specific properties and events that each one adds to the base class. As noted earlier, the declaration of HTML server controls on the page is the same as what you use for normal static HTML tags, with the addition of the

C H A P T E R 4 S E R V E R C O N T R O L S

109

runat="server" attribute. It is this attribute that allows ASP.NET to process them and translate them into instances of the corresponding .NET class. For this reason, the HTML server controls are a good option if you’re converting your existing HTML or ASP page to an ASP.NET web form.

Table 4-6. HTML Server Control Classes

Tag Declaration

.NET Class

Specific Members

<a runat="server">

HtmlAnchor

Href, Target, Title, Name,

 

 

ServerClick event

<button runat="server">

HtmlButton

CausesValidation,

 

 

ValidationGroup,

 

 

ServerClick event

<form runat="server">

HtmlForm

Name, Enctype, Method,

 

 

Target, DefaultButton,

 

 

DefaultFocus

<img runat="server">

HtmlImage

Align, Alt, Border, Height, Src,

 

 

Width

<input type="button"

HtmlInputButton

Name, Type, Value,

runat="server">

 

CausesValidation,

 

 

ValidationGroup, ServerClick

 

 

event

<input type="reset"

HtmlInputReset

Name, Type, Value

runat="server">

 

 

<input type="submit"

HtmlInputSubmit

Name, Type, Value,

runat="server">

 

CausesValidation,

 

 

ValidationGroup, ServerClick

 

 

event

<input type="checkbox"

HtmlInputCheckBox

Checked, Name, Type, Value,

runat="server">

 

ServerClick event

<input type="file"

HtmlInputFile

Accept, MaxLength, Name,

runat="server">

 

PostedFile, Size, Type, Value

<input type="hidden"

HtmlInputHidden

Name, Type, Value,

runat="server">

 

ServerChange event

<input type="image"

HtmlInputImage

Align, Alt, Border, Name, Src,

runat="server">

 

Type, Value, CausesValidation,

 

 

ValidationGroup, ServerClick

 

 

event

<input type="radio"

HtmlInputRadioButton

Checked, Name, Type, Value,

runat="server">

 

ServerChange event

<input type="text"

HtmlInputText

MaxLength, Name, Type,

runat="server">

 

Value, ServerChange event

<input type="password"

HtmlInputPassword

MaxLength, Name, Type,

runat="server">

 

Value, ServerChange event

<select runat="server">

HtmlSelect

Multiple, SelectedIndex,

 

 

Size, Value, DataSource,

 

 

DataTextField,

 

 

DataValueField, Items

 

 

(collection), ServerChange

 

 

event

Continued

110 C H A P T E R 4 S E R V E R C O N T R O L S

Table 4-6. Continued

Tag Declaration

.NET Class

Specific Members

<table runat="server">,

HtmlTable

Align, BgColor, Border,

<td runat="server">

 

BorderColor, CellPadding,

 

 

CellSpacing, Height, NoWrap,

 

 

Width, Rows (collection)

<th runat="server">

HtmlTableCell

Align, BgColor, Border,

 

 

BorderColor, ColSpan, Height,

 

 

NoWrap, RowSpan, Valign,

 

 

Width

<tr runat="server">

HtmlTableRow

Align, BgColor, Border,

 

 

BorderColor, Height, Valign,

 

 

Cells (collection)

<textarea runat="server">

HtmlTextArea

Cols, Name, Rows, Value,

 

 

ServerChange event

Any other HTML tag with the

HtmlGenericControl

None

runat="server" attribute

 

 

 

 

 

Note Two specialized HTML controls aren’t shown in Table 4-6. These are the HtmlHead and HtmlTitle controls, which provide server-side access to the <head> portion of a web page. Using these controls, you can dynamically set the title, metadata, and linked stylesheets for the page. Chapter 3 shows an example.

The meaning of most of the HTML server control properties is quite obvious, because they match the underlying HTML tag attributes. This means there’s no need to focus on each individual control. In the next few sections, you’ll get an overview of some common techniques for using controls and dig a little deeper into their events and the common object model.

Setting Style Attributes and Other Properties

The following example shows how you can configure a standard HtmlInputText control (which represents the <input type="text"> tag). To read or set the current text in the text box, you use the Value property. If you want to configure the style information, you need to add new CSS style attributes using the Style collection. Finally, if you want to set other attributes that aren’t exposed by any properties, you need to use the Attributes collection. This example uses the Attributes collection to associate some simple JavaScript code—showing an alert message box with the current value of the text box—to the client-side onFocus event of the control.

protected void Page_Load(object sender, System.EventArgs e)

{

//Perform the initialization only the first time the page is requested.

//After that, this information is tracked in view state.

if (!Page.IsPostBack)

{

// Set the style attributes to configure appearance. TextBox1.Style["font-size"] = "20px"; TextBox1.Style["color"] = "red";

//Use a slightly different but equivalent syntax

//for setting a style attribute. TextBox1.Style.Add("background-color", "lightyellow");

C H A P T E R 4 S E R V E R C O N T R O L S

111

// Set the default text.

TextBox1.Value = "<Enter e-mail address here>";

// Set other nonstandard attributes. TextBox1.Attributes["onfocus"] = "alert(TextBox1.value)";

}

}

If you request the page, the following HTML code will be returned for the text box:

<input name="TextBox1" id="TextBox1" type="text" style="WIDTH:410px;HEIGHT:46px;font-size:20px;color:red; background-color:lightyellow;" size="63" value="<Enter e-mail address here>" onfocus="alert(TextBox1.value)" />

Notice that the CSS style attribute also includes some information that wasn’t explicitly set in the code. Instead, Visual Studio added this information to the control tag when the control was resized in the development environment.

Figure 4-3 shows the resulting page when focus changes to the text box.

Figure 4-3. Testing HTML server controls

This process of control interaction is essentially the same for all HTML server controls. Style properties and attributes are always set in the same way. The only difference is that some controls expose additional properties that you can use. For example, the HtmlAnchor control exposes an Href property that lets you set the target page for the link.

Programmatically Creating Server Controls

Sometimes you don’t know in advance how many text boxes, radio buttons, table rows, or other controls you need because this might depend on other factors such as the number of records stored in a database or the user’s input. With ASP.NET, the solution is easy—you can simply create instances of the HTML server controls you need, set their properties with the object-oriented approach used in the previous example, and then add them to the Controls collection of the containing page. This technique was introduced in the previous chapter, and it applies equally well to HTML server controls and web controls.

112 C H A P T E R 4 S E R V E R C O N T R O L S

For example, the following code dynamically creates a table with five rows and four cells per row, sets their colors and text, and shows all this on the page. The interesting detail is that no control tags are declared in the .aspx file. Instead, everything is generated programmatically.

protected void Page_Load(object sender, System.EventArgs e)

{

//Create a new HtmlTable object. HtmlTable table1 = new HtmlTable();

//Set the table's formatting-related properties. table1.Border = 1;

table1.CellPadding = 3; table1.CellSpacing = 3; table1.BorderColor = "red";

//Start adding content to the table. HtmlTableRow row;

HtmlTableCell cell;

for (int i=1; i<=5; i++)

{

//Create a new row and set its background color. row = new HtmlTableRow();

row.BgColor = (i%2==0 ? "lightyellow" : "lightcyan");

for (int j=1; j<=4; j++)

{

//Create a cell and set its text. cell = new HtmlTableCell();

cell.InnerHtml = "Row: " + i.ToString() + "<br />Cell: " + j.ToString();

//Add the cell to the current row. row.Cells.Add(cell);

}

// Add the row to the table. table1.Rows.Add(row);

}

// Add the table to the page. this.Controls.Add(table1);

}

This example contains two nested loops. The outer loop creates a row. The inner loop then creates the cells and adds them to the Cells collection of the current row. When the inner loop ends, the code adds the entire row to the Rows collection of the table. The final step occurs when the outer loop is finished. At this point, the code adds the completed table to the Controls collection

of the page.

Figure 4-4 shows the resulting page.

C H A P T E R 4 S E R V E R C O N T R O L S

113

Figure 4-4. A dynamically generated table

This example used a table because it gave a good opportunity to show how child controls (cells and rows) are added to the Controls collection of the parent, but of course this mechanism works with any other server control.

Handling Server-Side Events

HTML server controls provide a sparse event model with two possible events: ServerClick and ServerChange. The ServerClick is simply a click that is processed on the server side. It’s provided by most button controls, and it allows your code to take immediate action. This action might override the expected behavior. For example, if you intercept the click event of a hyperlink control (the <a> element), the user won’t be redirected to a new page unless you provide extra code to forward the request.

The ServerChange event responds when a change has been made to a text or selection control. This event doesn’t occur until the page is posted back (for example, after the user clicks a submit button). At this point, the ServerChange event occurs for all changed controls, followed by the appropriate ServerClick.

Table 4-7 shows which controls provide a ServerClick event and which ones provide a ServerChange event.

Table 4-7. HTML Control Events

Event

Controls That Provide It

ServerClick

HtmlAnchor, HtmlForm, HtmlButton, HtmlInputButton, HtmlInputImage

ServerChange

HtmlInputText, HtmlInputCheckBox, HtmlInputRadioButton,

 

HtmlInputHidden, HtmlSelect, HtmlTextArea

 

 

114 C H A P T E R 4 S E R V E R C O N T R O L S

The ServerClick and ServerChange Events

The following example demonstrates the ServerClick and ServerChange events and shows you the order in which they unfold. To create this example, you need a text box, list box, and check box.

Here are the controls on the page:

<form id="Form1" runat="server"> <div>

<select runat="server" id="List1" size="5" multiple Name="List1"> <option>Option 1</option>

<option>Option 2</option> </select>

<br />

<input type="text" runat="server" ID="Textbox1" Size="10" Name="Textbox1"><br />

<input type="checkbox" runat="server" ID="Checkbox1" Name="Checkbox1">Option text<br />

<input type="submit" runat="server" ID="Submit1" Name="cmdSubmit" value="Submit Query">

</div>

</form>

Note that this code declares two list items for the list box and includes the multiple attribute. This means that the user will be able to select multiple items by holding down the Ctrl key while clicking each entry.

The text box and the check box are attached to the same event handler, while the list box uses a separate event handler with different code. The easiest way to set this up in Visual Studio is to create a text box event handler by double-clicking the text box. Then, rename the event handler to Ctrl_ServerChange(), and enter the code shown here:

protected void Ctrl_ServerChange(object sender, System.EventArgs e)

{

Response.Write("<li>ServerChange detected for " + ((Control)sender).ID + "</li>");

}

The actual event handler code is quite straightforward. It simply casts the sender object to a Control type, reads its ID property, and writes a message declaring that the event was detected.

Now, switch to the HTML source view, and edit the text box and check box tags to bind their ServerChange events to the new event handler, as shown here:

<input type="text" runat="server" ID="Textbox1" Size="10" Name="Textbox1" OnServerChange="Ctrl_ServerChange"><br /> <input type="checkbox" runat="server" ID="Checkbox1"

Name="Checkbox1" OnServerChange="Ctrl_ServerChange">

Note Visual Studio provides a greater level of design-time support for events with web controls. When working with web controls, you can attach event handlers using a special event view in the Properties window—you just need to click the lightning bolt icon. With HTML server controls, this facility isn’t available, although you can still coax Visual Studio into generating an event handler for the control’s default event by double-clicking it.

Next, double-click the HtmlSelect control to create an event handler for the list box. This event handler cycles through the control’s Items collection and writes the value of all the selected items to the web page, as follows:

C H A P T E R 4 S E R V E R C O N T R O L S

115

protected void List1_ServerChange(object sender, System.EventArgs e)

{

Response.Write("<li>ServerChange detected for List1. " + "The selected items are:</li><br />");

foreach (ListItem li in List1.Items)

{

if (li.Selected)

Response.Write("  - " + li.Value + "<br />");

}

}

Finally, the submit button handles the ServerClick event, as shown here:

protected void Submit1_ServerClick(object sender, System.EventArgs e)

{

Response.Write("<li>ServerClick detected for Submit1.</li>");

}

As an added bonus, when the page is created, the event handler for the Page.Load event adds another three items to the list box, provided the page is being requested for the first time. This shows how easy it is to programmatically add list items.

protected void Page_Load(object sender, System.EventArgs e)

{

if (!Page.IsPostBack)

{

List1.Items.Add("Option 3"); List1.Items.Add("Option 4"); List1.Items.Add("Option 5");

}

}

To test this page, request it in the browser, select some items in the list box, type some characters in the text box, select the check box, and click the submit button to generate a postback. You should end up with something similar to what’s shown in Figure 4-5.

Figure 4-5. Detecting change events

116 C H A P T E R 4 S E R V E R C O N T R O L S

Note that the order of change events is nondeterministic, and you shouldn’t rely on these events occurring in any set order. However, you’re likely to see events raised in the order in which the controls are declared. The only detail of which you’re guaranteed is that all the change events fire before the ServerClick event that triggered the postback.

Web Controls

HTML server controls provide a relatively fast way to migrate to ASP.NET but not necessarily the best way. For one thing, the names of HTML controls and their attributes are not always intuitive, and they don’t have the same design-time support for attaching event handlers. The HTML controls also have certain limitations, such as that style properties must be set through CSS syntax (which is more difficult than setting a direct property) and that change events can’t be raised until the page is posted back in response to another action. Finally, HTML server controls can’t provide user interface elements that aren’t already defined in the HTML standard. If you want to create some sort of aggregate control that uses a combination of HTML elements to render a complex interface, you’re on your own.

To address these issues, ASP.NET provides a higher-level web control model. All web controls are defined in the System.Web.UI.WebControl namespace and derive from the WebControl base class, which provides a more abstract, consistent model than the HTML server controls. Web controls also enable additional features, such as automatic postback. But the really exciting part is that many extended controls don’t just map a single HTML tag but instead generate more complex output made up of several HTML tags and JavaScript code. Examples include lists of check boxes, radio buttons, calendars, editable grids, and so on.

Figure 4-6 shows a portion of the inheritance hierarchy for web controls.

Figure 4-6. Web controls

C H A P T E R 4 S E R V E R C O N T R O L S

117

The WebControl Base Class

All the web controls inherit from the WebControl class. The WebControl class also derives from Control. As a result, many of its properties and methods—such as Controls, Visible, FindControl()—are similar to those of the HTML server controls. However, the WebControl class adds the properties shown in Table 4-8. Many of these properties wrap the CSS style attributes, such as the foreground or background color, the font, the height, the width, and so on. These properties allow you to configure the appearance of a web control much more easily (and with less chance of error).

Table 4-8. WebControl Class Properties

Property

Description

AccessKey

Returns or sets the keyboard shortcut that allows the user to quickly navigate to

 

the control. For example, if set to A, the user can move the focus to this control

 

by pressing Alt+A.

BackColor

Returns or sets the background color.

BorderColor

Returns or sets the border color.

BorderStyle

One of the values from the BorderStyle enumeration, including Dashed,

 

Dotted, Double, Groove, Ridge, Inset, Outset, Solid, and None.

BorderWidth

Returns or sets the border width.

CssClass

Returns or sets the CSS style to associate with the control. The CSS style can

 

be defined in a <style> section at the top of the page or in a separate CSS file

 

referenced by the page.

Enabled

Returns or sets the control’s enabled state. If false, the control is usually

 

rendered grayed out and is not usable.

Font

Returns an object with all the style information of the font used for the control’s

 

text. This property includes subproperties that can be set with the object-

 

walker syntax shown in this chapter.

ForeColor

Returns or sets the foreground color, for example, that of the text of the control.

Height

Returns or sets the control’s height.

TabIndex

A number that allows you to control the tab order. The control with a TabIndex

 

of 0 has the focus when the page first loads. Pressing Tab moves the user to the

 

control with the next lowest TabIndex, provided it is enabled. This property is

 

supported only in Internet Explorer 4.0 and higher.

ToolTip

Displays a text message when the user hovers the mouse above the control.

 

Many older browsers don’t support this property.

Width

Returns or sets the control’s width.

 

 

Basic Web Control Classes

ASP.NET includes a web control that duplicates each HTML server control and provides the same functionality. These web controls inherit from WebControl and add their own properties and events. Table 4-9 summarizes these core controls and their specific members.