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

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

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

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

Table 4-9. Basic Web Control Classes

ASP.NET Tag Declaration

Generated HTML

Key Members

<asp:Button>

<input type="submit"/> or

Text, CausesValidation, PostBackUrl,

 

<input type="button"/>

ValidationGroup, Click event

<asp:CheckBox>

<input type="checkbox"/>

AutoPostBack, Checked, Text,

 

 

TextAlign, CheckedChanged event

<asp:FileUpload>

<input type="file">

FileBytes, FileContent, FileName,

 

 

HasFile, PostedFile, SaveAs()

<asp:HiddenField>

<input type="hidden">

Value

<asp:HyperLink>

<a>...</a>

ImageUrl, NavigateUrl, Target, Text

<asp:Image>

<img/>

AlternateText, ImageAlign, ImageUrl

<asp:ImageButton>

<input type="image"/>

CausesValidation, ValidationGroup,

 

 

Click event

<asp:ImageMap>

<map>

HotSpotMode, HotSpots (collection),

 

 

AlternateText, ImageAlign, ImageUrl

<asp:Label>

<span>...</span>

Text, AssociatedControlID

<asp:LinkButton>

<a><img/></a>

Text, CausesValidation,

 

 

ValidationGroup, Click event

<asp:Panel>

<div>...</div>

BackImageUrl, DefaultButton,

 

 

GroupingText, HorizontalAlign,

 

 

Scrollbars, Wrap

<asp:RadioButton>

<input type="radio"/>

AutoPostBack, Checked,

 

 

GroupName, Text, TextAlign,

 

 

CheckedChanged event

<asp:Table>

<table>...</table>

BackImageUrl, CellPadding,

 

 

CellSpacing, GridLines,

 

 

HorizontalAlign, Rows (collection)

<asp:TableCell>

<td>...</td>

ColumnSpan, HorizontalAlign,

 

 

RowSpan, Text, VerticalAlign, Wrap

<asp:TableRow>

<tr>...</tr>

Cells (collection), HorizontalAlign,

 

 

VerticalAlign

<asp:TextBox>

<input type="test"/> or

 

<input type="test"/> or

 

<textarea>...</textarea>

AutoPostBack, Columns, MaxLength, ReadOnly, Rows, Text, TextMode, Wrap, TextChanged event

The properties of web controls are all fairly intuitive. One of the goals of web controls is to make it easier to set a control’s attributes through properties with consistent names, without having to worry about the details of how they translate to HTML code (although having a good knowledge of HTML certainly helps). For this reason, this chapter won’t describe and show examples for every type of control. Instead, we’ll provide a general discussion that’s useful for every control.

To start highlighting some of the key differences between HTML server controls and web controls, consider the following web control tag:

<asp:TextBox runat="server" ID="Textbox1" Text="This is a test" ForeColor="red" BackColor="lightyellow" Width="250px" Font-Name="Verdana" Font-Bold="True" Font-Size="20" />

Web controls are always declared on the page with the syntax <asp:controlname>, with the asp: prefix that makes them immediately recognizable as being different from the HTML controls. But this example also demonstrates a more dramatic difference—the way that style information is specified.

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

119

Essentially, this tag generates a text box control with a width of 250 pixels, a red foreground color, and a light yellow background. The text is displayed with the font Verdana, with a size of 20, and with bold formatting. The differences between the previous declaration and the respective declaration of a HTML tag are the following:

The control is declared using its class name (TextBox) instead of the HTML tag name (input).

The default content is set with the Text property, instead of a less obvious Value attribute.

The style attributes (colors, width, and font) are set by direct properties, instead of being grouped together in a single style attribute.

Web controls also have two special restrictions:

Every control declaration must have a corresponding closing tag or the empty element /> syntax at the end of the opening tag. In other words, ASP.NET tags follow the same rules as tags in XHTML. If you don’t close the tag, you’ll get a runtime error. Breaking this rule when working with HTML server controls has no adverse effect.

All web controls must be declared within a server-side form tag (and there can be only one server-side form per page), even if they don’t cause a postback. Otherwise, you’ll get a runtime error. This rule is not necessary when working with HTML server controls, provided you don’t need to handle postbacks.

If you request a page with this tag, you’ll see that the control is translated into the following HTML tag when the page is rendered:

<input name="Textbox1" type="text" value="This is a test" id="Textbox1" style="color:Red;background-color:LightYellow;font-family:Verdana; font-size:20pt;font-weight:bold;width:250px;" />

Units

All the control properties that use measurements, including BorderWidth, Height, and Width, require the Unit structure, which combines a numeric value with a type of measurement (pixels, percentage, and so on). This means when you set these properties in a control tag, you must make sure to append px (for pixel) or % (for percentage) to the number to indicate the type of unit.

Here’s an example with a Panel control that is 300 pixels wide and has a height equal to 50 percent of the current browser window:

<asp:Panel Height="300px" Width="50%" id="pnl" runat="server" />

If you’re assigning a unit-based property through code, you need to use one of the static methods of the Unit type. Use Pixel() to supply a value in pixels, and use Percentage() to supply a percentage value.

//Convert the number 300 to a Unit object

//representing pixels, and assign it. pnl.Height = Unit.Pixel(300);

//Convert the number 50 to a Unit object

//representing percent, and assign it. pnl.Width = Unit.Percentage(50);

You could also manually create a Unit object and initialize it using one of the supplied constructors and the UnitType enumeration. This requires a few more steps but allows you to easily assign the same unit to several controls.

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

// Create a Unit object.

Unit myUnit = new Unit(300, UnitType.Pixel);

// Assign the Unit object to several controls or properties. pnl.Height = myUnit;

pnl.Width = myUnit;

Enumerated Values

Enumerations are used heavily in the .NET class library to group a set of related constants. For example, when you set a control’s BorderStyle property, you can choose one of several predefined values from the BorderStyle enumeration. In code, you set an enumeration using the dot syntax:

ctrl.BorderStyle = BorderStyle.Dashed;

In the .aspx file, you set an enumeration by specifying one of the allowed values as a string. You don’t include the name of the enumeration type, which is assumed automatically.

<asp:TextBox BorderStyle="Dashed" Text="Border Test" id="txt" runat="server" />

Colors

The Color property refers to a Color object from the System.Drawing namespace. You can create Color objects in several ways:

Using an ARGB (alpha, red, green, blue) color value: You specify each value as integer.

Using a predefined .NET color name: You choose the correspondingly named read-only property from the Color class. These properties include all the HTML colors.

Using an HTML color name: You specify this value as a string using the ColorTranslator class.

To use these any of techniques, you must import the System.Drawing namespace, as follows:

using System.Drawing;

The following code shows several ways to specify a color in code:

// Create a color from an ARGB value.

int alpha = 255, red = 0, green = 255, blue = 0; ctrl.ForeColor = Color.FromARGB(alpha, red, green, blue);

//Create a color using a .NET name. ctrl.ForeColor = Color.Crimson;

//Create a color from an HTML code. ctrl.ForeColor = ColorTranslator.FromHtml("Blue");

When defining a color in the .aspx file, you can use any one of the known color names, as follows:

<asp:TextBox ForeColor="Red" Text="Test" id="txt" runat="server" />

Refer to the MSDN documentation for a full list of color names. Alternatively, you can use a hexadecimal color number (in the format #<red><green><blue>), as shown here:

<asp:TextBox ForeColor="#ff50ff" Text="Test" id="txt" runat="server" />

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

121

Fonts

The Font property actually references a full FontInfo object, which is defined in the System.Drawing namespace. Every FontInfo object has several properties that define a font’s name, size, and style. Even though the WebControl.Font property is read-only, you can modify all the FontInfo properties (shown in Table 4-10).

Table 4-10. FontInfo Properties

Property

Description

Name

A string indicating the font name (such as Verdana).

Names

An array of strings with font names, which are ordered by

 

preference.

Size

The size of the font as a FontUnit object. This can represent an

 

absolute or relative size.

Bold, Italic, Strikeout,

Boolean properties that either apply the given style attribute or

Underline, and Overline

ignore it.

 

 

In code, you can assign values to the various font properties as shown here:

ctrl.Font.Name = "Verdana"; ctrl.Font.Bold = true;

You can also set the size using the FontUnit type:

//Specifies a relative size. ctrl.Font.Size = FontUnit.Small;

//Specifies an absolute size of 14 pixels. ctrl.Font.Size = FontUnit.Point(14);

In the .aspx file, you need to use a special object-walker syntax to specify object properties such as font. The object-walker syntax uses a hyphen (-) to separate properties. For example, you could set a control with a specific font (Tahoma) and font size (40 point) like this:

<asp:TextBox Font-Name="Tahoma" Font-Size="40" Text="Size Test" id="txt" runat="server" />

or with a relative size, as follows:

<asp:TextBox Font-Name="Tahoma" Font-Size="Large" Text="Size Test" id="txt" runat="server" />

Of course, in the world of the Internet font names are just recommendations. If a given font isn’t present on a client’s computer, the browser attempts to substitute a similar font. (For more information on this font substitution process, refer to the CSS specification at http://www.w3.org/ TR/REC-CSS2/fonts.html.)

If you want to provide a list of possible fonts, you can use the FontInfo.Names property instead of the FontInfo.Name property. The Names property accepts an array of names that will be rendered as an ordered list (with greatest preference given to the names at the top of the list).

Tip The Names and Name properties are kept synchronized, and setting either one affects the other. When you set the Names property, the Name property is automatically set to the first item in the array you used for the Names property. If you set the Name property, the Names property is automatically set with an array containing a single item. Therefore, you should use only the Name property or the Names property, but not both at once.

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

Focus

Unlike HTML server controls, every web control provides a Focus() method. The focus control has an effect only for input controls (controls that can accept keystrokes from the user). When the page is rendered in the client browser, the user starts in the focused control. The Focus() method is new in ASP.NET 2.0.

For example, if you have a form that allows the user to edit customer information, you might call the Focus() method on the first text box with customer address information. That way, the cursor appears in this text box immediately. Also, if the text box is partway down the form, the page scrolls to the correct position automatically. Once the page is rendered, the user can move from control to control using the time-honored Tab key.

Of course, if you’re familiar with the HTML standard, you know there isn’t any built-in way to give focus to an input control. Instead, you need to rely on JavaScript. This is the secret to ASP.NET’s implementation. When your code is finished processing and the page is rendered, ASP.NET adds an extra block of JavaScript code to the end of your page. This JavaScript code simply sets the focus to the last control that had the Focus() method triggered. Here’s the code that’s needed to focus a control named TextBox2:

<script type="text/javascript"> <!--

WebForm_AutoFocus('TextBox2');// --> </script>

If you haven’t called Focus() at all, this code isn’t emitted. If you’ve called it for more than one control, the JavaScript code uses the more recently focused control.

Rather than call the Focus() method programmatically, you can set a control that should always be focused (unless you override it by calling the Focus() method). You do this by setting the DefaultFocus property, like so:

<form id="Form1" DefaultFocus="TextBox2" runat="server">

Incidentally, the focusing code relies on a JavaScript method named WebForm_AutoFocus(), which ASP.NET generates automatically. Technically, the JavaScript method is provided through an ASP.NET extension named WebResource.axd. The resource is named Focus.js. If you dig through the rendered HTML of your page, you’ll find an element that links to this JavaScript file that looks something like this:

<script src="WebResource.axd?a=s&r=WebForms.js"></script>

You can type this request directly into your browser to download and examine the JavaScript document. It’s quite lengthy, because it carefully deals with cases such as focusing on a nonfocusable control that contains a focusable child. However, the following code shows the heart of the focusing logic:

function WebForm_AutoFocus(focusId) {

//Find the element based on the ID (code differs based on browser). var targetControl;

if (__nonMSDOMBrowser) {

targetControl = document.getElementById(focusId);

}

else {

targetControl = document.all[focusId];

}

//Check if the control can accept focus or contains a child that can. var focused = targetControl;

if (targetControl != null && (!WebForm_CanFocus(targetControl)) ) {

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

123

focused = WebForm_FindFirstFocusableChild(targetControl);

}

// If there is a valid control, try to apply focus and scroll it into view. if (focused != null) {

try { focused.focus();

focused.scrollIntoView();

if (window.__smartNav != null) { window.__smartNav.ae = focused.id;

}

}

catch (e) {

}

}

}

As you can see, the first task this code performs is to test whether the current browser is an up-level version of Internet Explorer (and hence supports the Microsoft DOM). However, even if it isn’t, the script code still performs the autofocusing, with only subtle differences.

Another way to manage focus is using access keys. For example, if you set the AccessKey property of a TextBox to A, then when the user presses Alt+A, focus will switch to the TextBox. Labels can also get into the game, even though they can’t accept focus. The trick is to set the property Label.AssociatedControlID to specify a linked input control. That way, the label transfers focus

to the control nearby.

For example, the following label gives focus to TextBox2 when the keystroke Alt+2 is pressed:

<asp:Label AccessKey="2" AssociatedControlID="TextBox2" runat="server"> TextBox2:</asp:Label><asp:TextBox runat="server" ID="TextBox2" />

Access keys are also supported in non-Microsoft browsers, including Firefox.

The Default Button

Along with the idea of control focusing, ASP.NET 2.0 introduces a new mechanism that allows you to designate a default button on a web page. The default button is the button that is “clicked” when the user presses the Enter key. For example, on a form you might want to turn the submit button into a default button. That way, if the user hits Enter at any time, the page is posted back and the Button.Click event is fired for that button.

To designate a default button, you must set the HtmlForm.DefaultButton property with the ID of the respective control, as shown here:

<form id="Form1" DefaultButton="cmdSubmit" runat="server">

The default button must be a control that implements the IButtonControl interface. The interface is implemented by the Button, LinkButton, and ImageButton web controls but not by any of the HTML server controls.

In some cases, it makes sense to have more than one default button. For example, you might create a web page with two groups of input controls. Both groups may need a different default button. You can handle this by placing the groups into separate panels. The Panel control also exposes the DefaultButton property, which works when any input control it contains gets the focus.

Scrollable Panels

In ASP.NET 2.0, the Panel control gains the ability to scroll. This means you can fill your Panel controls with server controls or HTML, explicitly set the Height and Width properties of the panel so

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

they won’t be smaller than what’s required, and then switch on scrolling by setting the ScrollBars property to Vertical, Horizontal, Both, or Auto (which shows scrollbars only when there’s too much content to fit).

Here’s an example:

<asp:Panel ID="Panel1" runat="server" Height="116px" Width="278px" BorderStyle="Solid" BorderWidth="1px" ScrollBars="Auto">

This scrolls. <br /><br />

<asp:Button ID="Button1" runat="server" Text="Button" /> <asp:Button ID="Button2" runat="server" Text="Button" /> <br />

...

</asp:Panel>

Figure 4-7 shows the result.

Figure 4-7. A scrollable panel

The panel is rendered as a <div> tag. The scrolling behavior is provided by setting the CSS overflow attribute, which is supported in most browsers (starting with Internet Explorer 4.0 and Netscape 6.0).

Handling Web Control Events

Server-side events work in much the same way as the server events of the HTML server controls. Instead of the ServerClick events, there is a Click event, and instead of the generic ServerChange events there are specific events such as CheckedChanged (for the RadioButton and CheckButton) and TextChanged (for the TextBox), but the behavior remains the same.

The key difference is that web controls support the AutoPostBack feature described in the previous chapter, which uses JavaScript to capture a client-side event and trigger a postback. ASP.NET receives the posted-back page and raises the corresponding server-side event immediately.

To watch these events in action, it helps to create a simple event tracker application (see Figure 4-8). All this application does is add a new entry to a list control every time one of the events it’s monitoring occurs. This allows you to see the order in which events are triggered and the effect of using automatic postback.

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

125

Figure 4-8. The event tracker

In this demonstration, all control change events are handled by the same event handler:

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

<h3>List of events:</h3>

<asp:ListBox id="lstEvents" runat="server" Height="107px" Width="355px"/> <br /><br />

<h3>Controls being monitored for change events:</h3> <asp:TextBox id="txt" runat="server" AutoPostBack="true" OnTextChanged="CtrlChanged"/>

<br /><br />

<asp:CheckBox id="chk" runat="server" AutoPostBack="true" OnCheckedChanged="CtrlChanged"/>

<br /><br />

<asp:RadioButton id="opt1" runat="server" GroupName="Sample" AutoPostBack="true" OnCheckedChanged="CtrlChanged"/> <asp:RadioButton id="opt2" runat="server" GroupName="Sample" AutoPostBack="true" OnCheckedChanged="CtrlChanged"/>

</div>

</form>

The event handler simply adds a new message to a list box and scrolls to the end:

protected void CtrlChanged(Object sender, EventArgs e)

{

string ctrlName = ((Control)sender).ID; lstEvents.Items.Add(ctrlName + " Changed");

//Select the last item to scroll the list so the most recent

//entries are visible.

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

lstEvents.SelectedIndex = lstEvents.Items.Count - 1;

}

Note Automatic postback isn’t always a good thing. Posting the page back to the server interrupts the user for a brief amount of time. If the page is large, the delay may be more than a noticeable flicker. If the page is long and the user has scrolled to the bottom of the page, the user will lose the current position when the page is refreshed and the view is returned to the top of the page. Because of these idiosyncrasies, it’s a good idea to evaluate whether you really need postback and to refrain from using it for minor cosmetic reasons.

The Click Event and the ImageButton Control

In the examples you’ve looked at so far, the second event parameter has always been used to pass an empty System.EventArgs object. This object doesn’t contain any additional information—it’s just a glorified placeholder.

One control that does send extra information is the ImageButton control. It sends a special ImageClickEventArgs object (from the System.Web.UI namespace) that provides X and Y properties representing the location where the image was clicked. Using this additional information, you can create a server-side image map. For example, here’s the code that simply displays the location where the image was clicked and checks if it was over a predetermined region of the picture:

protected void ImageButton1_Click(object sender, System.Web.UI.ImageClickEventArgs e)

{

lblResult.Text = "You clicked at (" + e.X.ToString() + ", " + e.Y.ToString() + "). ";

if ((e.Y < 100) && (e.Y > 20) && (e.X > 20) && (e.X < 275))

{

lblResult.Text += "You clicked on the button surface.";

}

else

{

lblResult.Text += "You clicked the button border.";

}

}

The sample web page shown in Figure 4-9 puts this feature to work with a simple graphical button. Depending on whether the user clicks the button border or the button surface, the web page displays a different message.

Note Another, more powerful approach to handling image clicks is to create a server-side image map using the ImageMap control. The ImageMap control is demonstrated in Chapter 30, which deals with dynamic graphics.

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

127

Figure 4-9. Using an ImageButton control

The List Controls

The list controls are specialized web controls that generate list boxes, drop-down lists, and other repeating controls that can be either bound to a data source (such as a database or a hard-coded collection of values) or programmatically filled with items. Most list controls allow the user to select one or more items, but the BulletedList is an exception—it displays a static bulleted or numbered list. Table 4-11 shows all the list controls.

Table 4-11. List Controls

Control

Description

<asp:DropDownList>

A drop-down list populated by a collection of <asp:ListItems> objects.

 

In HTML, it is rendered by a <select> tag with the size="1" attribute.

<asp:ListBox>

A list box list populated by a collection of <asp:ListItems> objects.

 

In HTML, it is rendered by a <select> tag with the size="x" attribute,

 

where x is the number of visible items.

<asp:CheckBoxList>

Its items are rendered as check boxes, aligned in a table with one or

 

more columns.

<asp:RadioButtonList>

Like the <asp:CheckBoxList>, but the items are rendered as radio

 

buttons.

<asp:BulletedList>

A static bulleted or numbered list. In HTML, it is rendered using

 

the <ul> or <ol> tags. You can also use this control to create a list

 

of hyperlinks.

 

 

All the list controls support the same base properties and methods as other web controls. In addition, they inherit from the System.Web.UI.WebControls.ListControl class, which exposes the properties in Table 4-12. You can fill the lists automatically from a data source (as you’ll learn in Part 2), or you can fill them programmatically or declaratively, as you’ll see in the next section.