The Basic ASP.NET Web Form Controls


Apart from creating HTML elements using the HTML server controls, you can also use a set of controls that are part of ASP.NET, called the Web Form controls (or just Web Controls , after the namespace where they reside). These are all defined within the System.Web.UI.WebControls namespace. The basic controls that you can use and the equivalent HTML output that they generate are shown in the following table (the various types of list control will be covered in The ASP.NET List Controls section in this chapter):

ASP.NET Web Form control

Creates HTML element(s)

<ASP:HyperLink>

<a>...</a>

<ASP:LinkButton>

<a><img/></a>

<ASP:Image>

<img/>

<ASP:Panel>

<div>...</div>

<ASP:Label>

<span>...</span>

<ASP:Button>

<input type="submit"/> or <input type="button"/>

<ASP:TextBox>

<input type="text"/> or <input type="password"/> or <textarea>...</textarea>

<ASP:CheckBox>

<input type="checkbox"/>

<ASP:RadioButton>

<input type="radio"/>

<ASP:ImageButton>

<input type="image"/>

<ASP:Table>

<table>...</table>

<ASP:TableRow>

<tr>...</tr>

<ASP:TableCell>

<td>...</td>

Why Have Another Set of Controls?

It may seem odd to have a second set of server controls that apparently duplicate the existing HTML controls. In fact, there are a couple of good reasons for this. The ASP.NET Web Form controls are designed primarily to:

  • Make it easier for manufacturers and developers to build tools or applications those automatically generate the UI.

  • Simplify the process of creating interactive Web Forms, requiring less knowledge of the way that HTML controls work and making the task of using them less error-prone .

Both these requirements are met by providing a consistent and structured interface for the controls. Unlike HTML controls, all Web Form controls use the same property name for a specific value for the control. Contrast this with the HTML controls, where the size property (attribute) of a control might be the number of rows visible in a list box or the number of characters wide for a textbox. Meanwhile the number of characters wide for a <textarea> element is actually the cols property.

In the Web Form controls, the same property name is used across the controls. The property names are also more intuitive, for example the ASP:TextBox control has properties named TextMode , Rows , and Columns . By setting these in different combinations, the control will generate the appropriately sized <input> element or <textarea> element. You don't have to know the actual HTML output required; just set the control's properties of the control. It can even create a password-type <input> element if you set the appropriate value for the TextMode .

On top of this, the controls add extra features that are not usually available in the basic HTML controls. You can specify automatic postback of a form when a value in a control is changed. Several controls also create more than one HTML element; for example, they automatically add a text label to a checkbox or radio button.

The WebControl Base Class

Like the HTML controls, most Web Form controls inherit their members (properties, method, and events) from a base class. In this case, it is WebControl , defined within the System.Web.UI.WebControls namespace. This class provides a wide range of members, many of which are only really useful if you are building your own controls that inherit from WebControl . The public members used most often are shown in the following table:

Member

Description

Attributes property

Returns a collection of all the attribute name/value pairs within the .aspx file for this control. Can be used to read and set non-standard attributes (custom attributes that are not actually part of HTML) or to access attributes where the control does not provide a specific property for that purpose.

AccessKey property

Sets or returns the keyboard shortcut key that moves the input focus to the control.

BackColor property

Sets or returns the background color of the control.

BorderColor property

Sets or returns the border color of the control.

BorderStyle property

Sets or returns the style of border for the control, in other words, solid, dotted , double, and so on.

BorderWidth property

Sets or returns the width of the control border.

ClientID property

Returns the control identifier that is generated by ASP.NET.

Controls property

Returns a ControlCollection object containing references to all the child controls for this control within the page hierarchy.

Enabled property

Sets or returns a Boolean value indicating whether the control is enabled.

EnableViewState property

Sets or returns a Boolean value indicating if the control should maintain its viewstate and the viewstate of any child controls when the current page request ends.

Font property

Returns information about the font used in the control.

ForeColor property

Sets or returns the foreground color used in the control, usually the color of the text.

Height property

Sets or returns the overall height of the control.

ID property

Sets or returns the identifier specified for the control.

Page property

Returns a reference to the Page object containing the control.

Parent property

Returns a reference to the parent of this control within the page hierarchy.

Style property

References a collection of all the CSS style properties (selectors) that apply to the control.

TabIndex property

Sets or returns the position of the control within the tab order of the page.

ToolTip property

Sets or returns the pop-up text displayed when the mouse pointer is over the control.

Visible property

Sets or returns a Boolean value indicating whether the control should be rendered in the page output.

Width property

Sets or returns the overall width of the control.

DataBind() method

Causes data binding to occur for the control and all its child controls.

FindControl() method

Searches within the current container for a specified server control.

HasControls() method

Returns a Boolean value indicating whether the control contains any child controls.

DataBinding() event

Occurs when the control is being bound to a data source.

The Specific Web Form Control Classes

Each of the Web Form controls inherits from WebControl (or from another control that itself inherits from WebControl ), and adds its own task-specific properties, methods , and events. Those commonly used (for each control) are listed in the following table:

Control

Properties

Events

HyperLink

ImageUrl , NavigateUrl , Target , Text

- none -

LinkButton

CommandArgument , CommandName , Text , CausesValidation

OnClick() , OnCommand()

Image

AlternateText , ImageAlign , ImageUrl

- none -

Panel

BackImageUrl , HorizontalAlign , Wrap

- none -

Label

Text

- none -

Button

CommandArgument , CommandName , Text , CausesValidation

OnClick() , OnCommand()

TextBox

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

OnTextChanged()

CheckBox

AutoPostBack , Checked , Text , TextAlign

OnCheckedChanged()

RadioButton

AutoPostBack , Checked , GroupName , Text , TextAlign

OnCheckedChanged()

ImageButton

CommandArgument , CommandName , CausesValidation

OnClick() , OnCommand()

Table

BackImageUrl , CellPadding , CellSpacing , GridLines , HorizontalAlign , Rows

- none -

TableRow

Cells , HorizontalAlign , VerticalAlign

- none -

TableCell

ColumnSpan , HorizontalAlign , RowSpan , Text , VerticalAlign , Wrap

- none -

Literal

Text

- none -

PlaceHolder

- none -

- none -

It should be obvious from the names what most of the properties are for, but we will examine each control in the following sections, and indicate some of the things to look out for when you use them. The sample application (already seen in Chapter 5) shown in Figure 6-1 contains pages for most of the ASP.NET Web Form controls, and we will use these pages to demonstrate the properties of each control:

click to expand
Figure 6-1:
Note

You can get the sample files for this chapter from http://www.daveandal.net/books//. The application is in the server-controls folder. You can also run many of the examples online at the same URL.

Using the Web Form Controls

To add an ASP.NET Web Form server control to your page, define it just like an ordinary HTML element; by adding the appropriate 'attributes' for the properties you want to set. For example, you can add an ASP:TextBox control to the page to output an HTML textbox element using:

  <ASP:TextBox id="MyTextBox" BackColor="Red" Text="Enter a value..."   runat="server" />  

Notice that the Web Form controls all have the ASP namespace prefix (uppercase or lowercase, it doesn't matter which) to denote that they are from the System.Web.UI.WebControls namespace.

Setting Property Values from Enumerations

One thing that makes working with the HTML server controls used in the previous chapter easy is that all the properties are simple String values. For example, specify the string value right for the Align property of an HtmlImage control to align the image to the right of any following page content.

It is not always so straightforward with the ASP.NET Web Form controls. Many of the properties for the ASP.NET Web Form controls use values from an enumeration, or a reference to an object. For example, to align an image to the right of any following content when using an ASP.NET Image server control, set the ImageAlign property to the integer value that is defined for the enumeration member ImageAlign.Right .

In this example, the enumeration is named ImageAlign , and the member is named Right . Of course, this isn't a problem when you explicitly define the properties declaratively (in other words, by setting the attributes of a server control in the source of the page). The control knows from the property name which enumeration to use:

  <ASP:Image Src="mypic.gif" ImageAlign="Right" runat="server" />  

This produces the following HTML output (notice that in the Image control, border="0" is the default):

  <img src="mypic.gif" align="Right" border="0" />  

However, to assign a value to the property within the executable code of the page, you have to use the following:

  objMyImage.ImageAlign = ImageAlign.Right  

Even this is no good if you want to assign property values dynamically at runtime.

Creating Enumeration Values Dynamically

To assign property values dynamically at runtime (such as when they are selected from a list, as in our demonstration pages), you have to use the numeric value of the appropriate enumeration member. In the case of ImageAlign.Right , this value is 2 .

If you use a <select> list control for the values, you can set the Text of each <option> to the name in the enumeration, and set the Value to the integer that this equates to. The following code shows a <select> list containing the complete ImageAlign enumeration:

  <select id="selAlign" runat="server">   <option value="0">ImageAlign.NotSet</option>   <option value="1">ImageAlign.Left</option>   <option value="2">ImageAlign.Right</option>   <option value="3">ImageAlign.Baseline</option>   <option value="4">ImageAlign.Top</option>   <option value="5">ImageAlign.Middle</option>   <option value="6">ImageAlign.Bottom</option>   <option value="7">ImageAlign.AbsBottom</option>   <option value="8">ImageAlign.AbsMiddle</option>   <option value="9">ImageAlign.TextTop</option>   </select>  

Then, to set the ImageAlign property, just assign the value from the list directly to it:

  objMyImage.ImageAlign = selAlign.Value  

Or you can be more specific and use the SelectedIndex property of the list:

  objMyImage.ImageAlign = selAlign.Items(selAlign.SelectedIndex).Value  
Finding Enumeration Values

Of course, the next obvious question would be, "how do I go about finding out the values to use for an enumeration?" In fact there are a few options here. Most enumerations provide a type converter that can be used to get the value given the enumeration member as a string. In Visual Basic, you can use:

  TypeDescriptor.GetConverter(GetType(  enumeration  )).ConvertFromString("  member  ")  

To be able to create a TypeDescriptor object and use its methods in your code, import the System.ComponentModel namespace that contains the definition of the TypeDescriptor class:

  <%@Import Namespace="System.ComponentModel" %>  

For example, to get the value of HorizontalAlign.Left , you can use:

  TypeDescriptor.GetConverter(GetType(HorizontalAlign)).ConvertFromString("Left")  

Alternatively, for enumerations that don't provide a type converter, you can usually cast the enumeration member directly to an Integer variable:

  Dim intValue = CType(HorizontalAlign.Left, Integer)  

Another technique is to use the excellent WinCV utility that is included with the frameworks. Simply type in all or part of the name of the enumeration, select it in the left-hand pane and the values are displayed in the right-hand pane (see Figure 6-2). You can even click on the Option button in the top right-hand side of the window to copy them to the clipboard to paste into your code (but note that the values are hexadecimal ):

click to expand
Figure 6-2:

WinCV is installed in the Program Files\Microsoft Visual Studio.NET\FrameworkSDK\Bin folder if you have VS.NET, or the Program Files\Microsoft.NET\SDK\[version]\FrameworkSDK\Bin folder if you just installed the .NET Framework.

Setting Properties That Are Objects

The second area where working with the ASP Web Form controls can be a little tricky is when you want to set (or retrieve) property values that are actually references to other objects. A typical example of something that should be simple but actually isn't when you first try it is setting the value of a 'color' property. It's not that Microsoft's developers were trying to make life awkward “it's done on purpose to provide extra features within the controls and the framework as a whole. It also allows strong typechecking to be achieved by the compiler and better support in a designer tool such as Visual Studio, which would not be possible if they were string values.

As an example, the ASP Web Form controls have several properties ( BackColor , ForeColor , BorderColor ) that reference a Color object rather than a simple string value. When you explicitly define the colors for the controls in your source code, use the color names directly:

  <asp:textbox id="MyText" Text="This is a textbox" runat="server"   BackColor="Red" ForeColor="White" />  

However, to assign colors at runtime, you have to first create a Color object and then assign this object to the appropriate property. For this, use the shared properties and methods that the Color class exposes.

The System.Drawing.Color Class

The Color class defines shared properties for all of the standard HTML color names, such as AliceBlue , AntiqueWhite , and so on. It also exposes three shared methods that create a Color object, as shown in the following table:

Method

Description

FromArgb

Creates a Color object from its 32-bit component values that define the alpha , red , green , and blue elements.

FromKnownColor

Creates a Color object from a specified HTML standard 'known color' name; for example, AliceBlue or Gainsboro .

FromName

Creates a Color object using the specified name, which can be a 'known color' name, a 32-bit value or a hexadecimal HTML-style color value such as #ff0000 (red).

Each Color object also has properties that return the individual components of the current color. For example, the properties A , B , G , and R return the alpha, blue, green, and red components respectively. To get the name of the color if it is one of the 'known colors', query the Name property of the Color object.

To be able to create a Color object and use its shared properties and methods in your code, import the System.Drawing namespace, which contains the definition of the Color class:

  <%@Import Namespace="System.Drawing" %>  

In our demonstration pages, there are textboxes where you can enter the colors you want for various properties of the control. For example, to set the BackColor property of a control, call the FromName() method (passing it the value that was entered), and then assign the object that this method creates to the BackColor property of the control:

  MyControl.BackColor = Color.FromName(txtBackColor.Value)  

To retrieve the color from the BackColor property, extract the Name of the Color object that the property references:

  txtForeColor.Value = MyControl.ForeColor.Name  
The System.Web.UI.WebControls.Unit Class

Several properties of the ASP Web Form controls are references to a Unit object; for example, the Width and Height of an Image control and the BorderWidth of a Table control. As with the Color properties, you don't have to concern yourself with this when explicitly defining the values in your sourcecode:

  <asp:image id="MyImage" Src="mypic.gif" runat="server"   Height="100px" Width="50%" />  

However, to assign values at runtime, you have to use the properties and methods exposed by the Unit object. The class that defines the Unit object is part of the same namespace as the ASP.NET Web Form controls, and so it is imported by default into your ASP pages. It exposes the two properties shown in the following table:

Property

Description

Type

The type of unit that the value is measured in. Member of the UnitType enumeration ( Cm , Mm , Em , Ex , Inch , Percentage , Pica , Pixel , or Point ).

Value

The number of units (as defined in the Type property) that make up the value.

The Unit class also provides three shared methods that you can use to create a Unit object with a specific Type property value. These are shown in the following table:

Method

Description

Percentage()

Creates a Percentage type Unit object using specified 32-bit signed integer.

Pixel()

Creates a Pixel type Unit object using specified 32-bit signed integer.

Point()

Creates a Point type Unit object using specified 32-bit signed integer.

So, if you have an Integer variable named intTheHeight that contains the value in pixels to be set for the Height property of a control named MyControl , use:

  MyControl.Height = Unit.Pixel(intTheHeight)  

If the value comes from a textbox with the id of txtHeight , use:

  MyControl.Height = Unit.Pixel(txtHeight.Value)  

To set the value as a percentage (say you wanted the control to be 50 percent of the width of the page or its container), use:

  MyControl.Height = Unit.Percentage(50)  

To retrieve the value of the Height property from the control, query the Unit object's Value property. The following code returns 100 for the Image control used earlier in this section:

  txtHeight.Value = MyControl.Height.Value  

If you want to know the type of unit, query the Type property of the Unit object, but this returns the integer equivalent of the UnitType enumeration. For a unit in pixels, for example, this property returns 1 . However (in a way similar to the example with the HorizontalAlign enumeration), you can use a type converter to get the text name. This time, use the ConvertToString() method rather than the ConvertFromString() method:

  TypeDescriptor.GetConverter(GetType(UnitType)).ConvertToString _   (MyControl.Height.Type)  

Finally, the easiest way to get the complete value in human-readable form (including the unit type) is to use the ToString() method. For the same control, the following code returns 100px :

  txtHeight.Value = MyControl.Height.Value.ToString()  

Using the AutoPostBack Feature

Certain Web Form server controls in ASP.NET ( TextBox , CheckBox , and RadioButton ), and all the list controls provide a property named AutoPostBack . By default, this property is False . If you set it to True for a control, that control will automatically post its value, and the values of the rest of the controls on the same form, back to the server when the user selects a value.

This also raises an event on the server that you can handle and use to update the contents of the page. You can experiment with AutoPostBack in the samples provided; handling the events on the server is discussed later in the chapter.

The mechanism to implement automatic postback is simple. It uses exactly the same techniques as when you program it in a <form> page. When the AutoPostBack property is True , the server control adds a client-side event to the control “for a button-type control, it is the onclick event, and for textboxes and list controls, it is the onchange event:

  <input id="MyControl" type="checkbox" name="MyControl"   onclick="javascript:__doPostBack('MyControl','')" />  

This causes a client-side function named __doPostBack to run when the control is clicked, when the selection is changed in a list, or when the user edits the content of a textbox and moves to another control. The ID of the control is passed to this function as well.

At the same time, the <form> on which the control resides has two extra hidden -type <input> controls added to it. These are used to pass back to the server the ID of the control that was clicked or changed, and any value for the second parameter that the __doPostBack() function receives:

  <input type="hidden" name="__EVENTTARGET" value="" />   <input type="hidden" name="__EVENTARGUMENT" value="" />  

And, of course, the client-side __doPostBack() function is added to the page as well. It just collects the control name and any arguments, puts them into the hidden controls, and submits the form to the server:

  <script language="javascript">      <!--    function __doPostBack(eventTarget, eventArgument) {    var theform;         if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1) {       theform = document.forms["_ctl0"];    }         else {       theform = document._ctl0;    }    theform.__EVENTTARGET.value = eventTarget.split("$").join(":");    theform.__EVENTARGUMENT.value = eventArgument;    theform.submit(); }      // --> </script>  
Note

Microsoft issues a hot fix to solve some issues with the doPostBack code in v1.1. If you find that Netscape browsers do not work correctly with your pages, you may need to install this hotfix . More details are available from http://support.microsoft.com/default.aspx?scid=kb;en-us;818803

Examples of the ASP Web Form Controls

This section briefly looks at each of the basic ASP.NET Web Form controls to give you a flavor for what they do and how they can be used. We will bring out any particularly important points about each control as we go.

The ASP:CheckBox and ASP:RadioButton Controls

These controls create individual checkboxes and radio buttons (later you'll see two controls that can create lists of checkboxes or radio buttons automatically). One extremely useful feature of the CheckBox and RadioButton controls is that they automatically create a label for the control using the value of the Text property. You can place this label to the left or right of the control using the TextAlign property, as shown in Figure 6-3:

click to expand
Figure 6-3:

The sourcecode used for creating the server control in this page is:

  <ASP:CheckBox id="MyControl" Text="My CheckBox" runat="server" />  

You can also use this page to experiment with the effects of the AutoPostBack property discussed earlier. Also notice the AccessKey and ToolTip that make it seem like a real Visual Basic style control. These are, of course, client-side features ( ToolTip sets the title attribute of the element), but they are part of the HTML 4.0 standards.

Adding Styles to Web Form Controls

The formatting features that apply to all the ASP Web Form controls are demonstrated in the screenshot of the CheckBox control in Figure 6-4. You can see how they add a set of CSS-style properties (or selectors) to the element:

click to expand
Figure 6-4:
Setting the Group Name for a RadioButton Control

The RadioButton control is almost identical to the CheckBox control, except (of course) that it creates an <input type="radio"> element instead of an <input type="checkbox"> element. However, there is one more fundamental difference. The RadioButton control exposes an extra property called GroupName , which sets the name attribute of the control. You can see this in Figure 6-5:

click to expand
Figure 6-5:

The sourcecode used for creating the server control in this page is:

  <ASP:RadioButton id="MyControl" Text="My RadioButton" runat="server" />  

This feature is required for two reasons. One is the obvious reason that you must use the same name attribute for all radio buttons that you want to be part of the same mutually exclusive group. The second reason is that all the controls on a page must have a unique ID property, and this is automatically used as the name attribute as well (as you can see if you refer back to the screenshot of the CheckBox control). Unlike the HTML radio button control there is no Name property for the ASP.NET Web Form RadioButton control, so the GroupName is the only way to set the name attribute.

The ASP:HyperLink Control

This control provides an easy way to create hyperlink <a> elements. In addition to the usual formatting, AccessKey , and ToolTip properties, it provides specific properties for the NavigateUrl (which sets the href attribute) and the Target property (which sets the target attribute). One other great feature is that you can set the text that appears as the hyperlink (the content of the resulting <a> element) using the Text property, as shown in Figure 6-6:

click to expand
Figure 6-6:

The sourcecode used for creating the server control in this page is:

  <ASP:Hyperlink id="MyControl" Text="My Hyperlink"   NavigateUrl="asp_hyperlink.aspx" runat="server" />  

Notice that once again there is no Name property. This seems to indicate that the control can't be used to create an anchor in a page that another hyperlink can target. An HTML anchor element requires the name attribute to be set:

  <a name="para1">Paragraph One</a>  

The location is targeted in the page using an HTML element such as:

  <a href="thepage.aspx#para1">Go To Paragraph One</a>  

However, you can add a name attribute to a Hyperlink control either declaratively or programmatically. It can be declaratively done by specifying it within the element in the source of the page:

  <ASP:Hyperlink Name="para1" id="MyAnchor" Text="text-for-link"   NavigateUrl="url-to-go-to" runat="server" />  
Using the Attributes Property with Server Controls

One other solution at runtime is to use the Attributes property to add the attribute programmatically. This property gives you access to a collection of all the HTML attributes on a server control. So, you can access the name attribute using:

  strNameAttr = MyAnchor.Attributes("name")  

And can set or change the name attribute using:

  MyAnchor.Attributes("name") = strNewName  

So, you can still achieve what you want without a Name property. This useful technique can be applied to any server control, including the HTML server controls you saw in the previous chapter. It may be useful in other cases where you want to add non-standard attributes to elements for your own purposes.

Using an Image as a Hyperlink

Often, images are used as hyperlinks in pages, and the Hyperlink control makes this much easier than coding by hand. If you specify the path to an image file as the ImageUrl property, that image is used in place of the Text property as the content of the <a> element, as shown in Figure 6-7. We've provided a few images for you to try out.

click to expand
Figure 6-7:

The ASP:LinkButton Control

The LinkButton control demonstrates an interesting extension to the use of an HTML <a> element. By default it uses the AutoPostBack feature described earlier, specifying the client-side __doPostBack JavaScript function as the href attribute of an <a> element. This means that whenever the link is clicked, the form will be posted back to the server, where a Click event will be raised. You can see the JavaScript function in the status bar in Figure 6-8:

click to expand
Figure 6-8:

The sourcecode used for creating the server control in this page is:

  <ASP:LinkButton id="MyControl" Text="My LinkButton" runat="server" />  

The clickable text is specified using the Text property in the same way as with a Hyperlink control, but in this control there is no option to use an image instead of text. For that, use an ImageButton control (described shortly) instead.

The ASP:Image Control

To display an image in your page and be able to access the control in your server-side code, you can use the ASP.NET Image server control. There are properties available that specify all the usual attributes for an <img> element, including the size, an AccessKey , the ToolTip , the alignment in relation to surrounding content, the border style, and the border and background colors, as shown in Figure 6-9:

click to expand
Figure 6-9:

The sourcecode for creating the server control in this page is:

  <ASP:Image id="MyControl" ImageUrl="BookmarkButton.gif" runat="server" />  

We have provided a few images for you to experiment with. Notice how you can specify the values for the Color properties ( BorderColor in the screenshot) using a standard HTML-style hexadecimal color value.

The ASP:Panel Control

While it might sound like an exotic new feature to use in your pages, the Panel control is actually just a way of creating a formatted HTML <div> element. You can specify the size and style of the element, and add a background image (though you should realize that as with all the server controls, some browsers may not support all the style properties you apply). Figure 6-10 shows the results:

click to expand
Figure 6-10:

The sourcecode used for creating the server control in this page is:

  <ASP:Panel id="MyControl" Text="My Panel" runat="server">   Some text inside the Panel control</ASP:Panel>  

A useful feature is the ability to set the width of the control, and then turn text wrapping on and off using the Wrap property. Remember that you can also add extra style properties to any server control using the Style collection:

  MyControl.Style(  "    selector-name    "  ) =  "    value    "   

You could specify that the <div> should be absolutely positioned on the page, add scroll bars to it, change the font, and so on, just by adding the appropriate CSS selector values.

The ASP:Label Control

The Panel control you just saw creates an HTML <div> element, and this is not always ideal. For example, it automatically wraps to the next line and causes other content to be wrapped below it. To place content inline with other elements and text, you need an HTML <span> element instead. This is just what the ASP.NET Label control provides. This control has the usual set of properties that define the appearance: ToolTip , AccessKey , and so on. It also has the Text property that can be used to specify the content of the <span> element, as shown in Figure 6-11:

click to expand
Figure 6-11:

The sourcecode used for creating the server control in this page is:

  <ASP:Label id="MyControl" Text="My Label" runat="server" />  

The ASP:Button Control

The ASP.NET Button control is used to create a standard HTML button that you can access in server- side code. Again, its properties are the usual set seen in all the other controls. Notice that the type of <input> element it creates is a submit button. Clicking the button will automatically submit the form on which it resides to your server, where you can handle the Click event it raises in your server-side code. Figure 6-12 shows the Button control:

click to expand
Figure 6-12:

The sourcecode used for creating the server control in this page is:

  <ASP:Button id="MyControl" Text="My Button" runat="server" />  

The ASP:ImageButton Control

Instead of using a normal text-captioned button to raise a Click event on the server, you can use a clickable image instead. The ImageButton control creates an <input type="image"> element that submits the form it resides on to the server when clicked. Also, as shown in Figure 6-13, you can control the size and appearance of the image to get the desired effect:

click to expand
Figure 6-13:

The sourcecode used for creating the server control in this page is:

  <ASP:ImageButton id="MyControl" ImageUrl="BookmarkButton.gif"   runat="server" />  

The ASP:TextBox Control

One of the most complex of the basic Web Form input controls is the TextBox control. You can use this to create several different types of HTML elements, including a normal single-line textbox, a multi-line textbox (where it actually creates an HTML <textarea> element), and a password input box that displays asterisks instead of text.

In its simplest form, to create a normal <input type="text"> element, the default property values suffice. However, the MaxLength , ReadOnly , and ToolTip properties are set as seen in Figure 6-14. The Columns property, which equates to the size attribute for an <input type="text"> element is also set:

click to expand
Figure 6-14:

The sourcecode used for creating the server control in this page is:

  <ASP:TextBox id="MyControl" Text="My TextBox" runat="server" />  

We've turned on AutoPostBack as well, and if you do the same and experiment, you will find that you can type in the textbox as usual, but when you move the input focus to another control (by pressing the Tab key or by clicking on another control with the mouse), the page is automatically submitted to the server where it will raise a Change event that you could create an event handler for. You'll see more about this later in this chapter.

Creating a Multi-Line Textbox

Figure 6-15 shows how to create an HTML <textarea> element that acts as a multi-line textbox using the ASP.NET TextBox control. Just change the value of the TextMode property to TextBoxMode.MultiLine , and specify the appropriate number of Rows and Columns :

click to expand
Figure 6-15:
Creating a Password Input Element

The third option for the TextMode property is TextBoxMode.Password . When this is selected, as shown in Figure 6-16, the control creates an <input type="password"> HTML element:

click to expand
Figure 6-16:
Note

Textboxes always persist their state (text) when placed on an HTML form, even if you turn off viewstate by setting EnableViewState=False . This is because they always post their value back to the server from a form and cause an update event.

The ASP:Table Control

A useful ASP.NET Web Form control is the Table control. This is very similar to the HtmlTable server control discussed in the previous chapter. However, it also provides the standard Web Form range of control properties for the appearance of the table. Figure 6-17 shows a formatted table and the output that the control creates to implement the table in the browser. At the bottom of the page, you can see the values set for the properties. The drop-down lists for the number of rows and columns help specify what size the generated table should be:

click to expand
Figure 6-17:
Creating the Table

The way to dynamically create the table is very similar to how you did it with the HtmlTable server control in the previous chapter. Of course, the object class names are different ( TableRow and TableCell instead of HtmlTableRow and HtmlTableCell ). The differences between the example in the previous chapter and this one are highlighted in the following code:

 Dim intRows As Integer = selRows.Value Dim intCols As Integer = selCols.Value Dim intRowCount, intColCount As Integer  Dim objRow As TableRow   Dim objCell As TableCell  For intRowCount = 0 To intRows - 1  objRow = New TableRow()  For intColCount = 0 To intCols - 1  objCell = New TableCell()   objCell.Controls.Add(New LiteralControl ("R" & intRowCount _   & "C" & intColCount))  objRow.Cells.Add(objCell)       Next    MyControl.Rows.Add(objRow) Next 

Also, you have to use a different technique to insert the values into the cells of the table. In the HtmlTable example, you simply set the InnerHtml property of the cells. You can't do that here because the TableCell object doesn't have an InnerHtml property. Instead, use LiteralControl objects to generate the cell content.

Using a LiteralControl Object to Generate Content

The LiteralControl object provides no inherent formatting or content “in other words, it doesn't create any HTML elements. It simply inserts an instruction into the code when the page is compiled (actually a Write statement) that outputs the value of the control.

So, to output the content for each cell, just instantiate a new LiteralControl object and pass as the single String -type parameter the text, HTML or other content that you want to be generated. You can, of course, use a LiteralControl where you want to generate some content without placing it inside another HTML element.

The ASP:Literal and ASP:PlaceHolder Controls

Two controls not included in the demonstration application, but which you may find uses for in your own pages, are the ASP:Literal and the ASP:PlaceHolder controls. We will describe these two controls here for completeness.

The ASP:Literal Control

The ASP:Literal control was used in the previous example where you dynamically created a table using the ASP:Table control. Other than the common members inherited from the base class Control , it has only a single property named Text . This defines the text that is output by the control. It generates no other output (no HTML elements, for example), and so it is useful where all you want to do is place some text in the page:

  <ASP:Literal Text="Some Text Here" runat="server" />  

The value used for the Text property can, however, contain HTML. For example, you can use it to create custom elements in the output for which there is no server control available:

  <ASP:Literal Text="<gloop>A custom element</gloop>" runat="server" />  

As you'd expect, this produces the following (probably not very useful) output:

  <gloop>A custom element</gloop>  
The ASP:PlaceHolder Control

The final control you will look briefly at is the ASP:PlaceHolder control. This is used when creating controls dynamically in a page, rather than by declaring them explicitly within the source of the page. For example, you can insert an ASP:PlaceHolder into the page like this:

  <ASP:PlaceHolder id="MyPlaceHolder" runat="server" />  

Then, you can insert three ASP:TextBox controls into the page using the following code:

  <script runat="server">   Sub Page_Load()   Dim intLoop As Integer   Dim objTextBox As TextBox   For intLoop = 1 To 3   objTextBox = New TextBox()   MyPlaceHolder.Controls.Add(objTextBox)   Next   End Sub   </script>  

The result when viewed in the browser is just the three new textboxes “ the PlaceHolder control doesn't create any output of its own:

  <input name="ctrl0" type="text" /><input name="ctrl1" type="text" />   <input   name="ctrl2" type="text" />  

Reacting to Click and Change Events

As with the HTML controls, the ASP.NET Web Form controls raise events that you can react to on the server. The Events demonstration page (see Figure 6-18) shows the Click and Change events that are exposed by most of the Web Forms. It neatly demonstrates the way that the Change event is raised when you edit the content of a textbox and then press the Tab key or move to another control by clicking with the mouse. A message indicating that a Change event was detected , and showing the source control's id , is displayed at the bottom of the page:

click to expand
Figure 6-18:

The code in the page also detects events for any of the other controls. For example, you can click the ImageButton control, and in this case you get the coordinates of the mouse pointer within the control displayed (see Figure 6-19):

click to expand
Figure 6-19:

The Code in the Events Demonstration Page

The code used in this page is very similar to that used for the HTML controls in the previous chapter. Each of the non-button controls on the page has the AutoPostBack property set to True , so that clicking or changing the control's contents will automatically submit the page to the server (the button-type controls do this automatically). Also, each control has an event handler specified for the appropriate Click or Change property. Notice that they have specific event names depending on the control type:

  <asp:TextBox id="MyText" Text="OriginalValue" runat="server"   OnTextChanged="MyChangeCode" AutoPostBack="True" />     <asp:CheckBox id="MyCheckbox" Text="My CheckBox" runat="server"   OnCheckedChanged="MyChangeCode" AutoPostBack="True" />     <asp:ImageButton id="MyImageButton" ImageUrl="ClickmeButton.gif"   runat="server" ImageAlign="absbottom" OnClick="MyImageCode" />     <asp:Button id="MyButton" Text="Submit" runat="server"   OnClick="MyClickCode" />  
Note

We haven't included the list controls here. They are described in the next section of the chapter, where we will investigate how we get the selected value(s) from these controls.

There is also a <div> , for displaying the messages about the events detected:

  <div id="divResult" runat="server" EnableViewState="False" />  

The event handlers for the textbox, checkbox, and button controls are shown in the code that follows . You can see that the ImageButton event code accepts an ImageClickEventArgs object as the second argument (from where it extracts the coordinates of the mouse pointer), while the handlers for the other controls accept an ordinary EventArgs object for the second parameter:

  Sub MyChangeCode(objSender As Object, objArgs As EventArgs)   divResult.InnerHtml &= "Change event detected for control '" _   & objSender.ID & "'"   End Sub     Sub MyImageCode(objSender As Object, objArgs As ImageClickEventArgs)   divResult.InnerHtml &= "Click event detected in control '" _   & objSender.ID & "' at X=" & objArgs.X _   & " Y=" & objArgs.Y   End Sub     Sub MyClickCode(objSender As Object, objArgs As EventArgs)   divResult.InnerHtml &= "Click event detected for control '" _   & objSender.ID & "'"   End Sub  
Working with Command Controls

Three of the button-type controls “ Button , ImageButton , and LinkButton “provide a command feature as well as supporting the standard events. You can set the two properties CommandName and CommandArgument to any string values you want. When that button is clicked, it raises a Command event on the server to which you can respond. You can see this in the Commands demonstration page shown in Figure 6-20:

click to expand
Figure 6-20:

The Code in the Commands Demonstration Page

Each time the page is loaded, it assigns the values from the textboxes on the page to the CommandName and CommandArgument properties of the three button controls. The page also contains the event handler shown in the following code, which is executed when a Command event occurs. It extracts the ID , CommandName , and CommandArgument properties of the button control that raised the event, and displays them:

  Sub MyCommandCode(objSender As Object, objArgs As CommandEventArgs)   divResult.InnerHtml &= "Command event detected for control '" _   & objSender.ID & "'<br />" _   & "CommandName is '" _   & objSender.CommandName _   & "', CommandArgument is '" _   & objSender.CommandArgument & "'"   End Sub  

This feature is useful in some couple of scenarios. Suppose you have more than one button control on a form, you can use this feature to detect which button was clicked to submit the form. In previous versions of ASP, this was normally achieved by examining the Request.Form collection (or Request.QueryString if the form has its method set to GET ) to see which button was clicked. You just looked for the specific name or value of the button.

With a Command event, you can use a Select Case construct to figure out which button raised the event instead of searching the Request.Form and Request.QueryString collections. You only have to check the CommandName value. This provides a far better structure to your code, and means that it is easier to add more buttons or change the caption or name of existing ones without breaking the code. You can also use different values for the CommandArgument property to pass your own custom control-specific or task-specific values to the event handler. The second useful scenario is when you work with the complex list controls, in particular the DataGrid control. By setting pre-defined values for the CommandName property, you can use the buttons for control-specific tasks when editing data in the DataGrid control. This is described in Chapter 7.




Professional ASP. NET 1.1
Professional ASP.NET MVC 1.0 (Wrox Programmer to Programmer)
ISBN: 0470384611
EAN: 2147483647
Year: 2006
Pages: 243

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