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

ASP .NET Web Developer s Guide - Mesbah Ahmed, Chris Garrett

.pdf
Скачиваний:
37
Добавлен:
24.05.2014
Размер:
7.32 Mб
Скачать

110 Chapter 3 • ASP Server Controls

Using HyperLink Controls

The HyperLink server control enables us to link to a different page. Its Text property is displayed on the screen as a hyperlink. On click of the hyperlink, it links to a page specified in its NavigateUrl property.The displayed text can be replaced by an image by specifying the ImageUrl property. In our next example, we will develop a page with two HyperLink controls. One of them will display text, and the other will display an image.We will specify the “http://ahmed2/Chapter3/ ServerControl4.aspx” in both of their NavigateUrl properties.The completed application will be displayed in IE as shown in Figure 3.46.When the user clicks any of the controls, the system will display the specified page.The complete code for the application is shown in Figure 3.47 and is also available in a file named HyperLink1.aspx in the accompanying CD.

Figure 3.46 Illustration of the HyperLink Server Control

Figure 3.47 Complete Listing for HyperLink1.aspx

<!— Chapter3\HyperLink1.aspx —>

<%@ Page Language="VB" Debug="true" %> <html><head></head><body>

<form runat="server">

<asp:HyperLink id="HyperLink1" runat="server"

NavigateUrl="http://ahmed2/Chapter3/ServerControl4.aspx"

Text="Go to a simple page"/><br><br>

<asp:HyperLink id="HyperLink2" runat="server"

NavigateUrl="http://ahmed2/Chapter3/ServerControl4.aspx"

ImageUrl="http://ahmed2/Chapter3/BaitcastReel1.jpg"

Continued

www.syngress.com

ASP Server Controls • Chapter 3

111

Figure 3.47 Continued

Text="World's Best Fishing Reel"/><br><br>

</body></form></html>

Binding a ListControl to an ArrayList

In most of our previous examples, we loaded a list box via code in the Page_Load event. In this section, we will introduce an important concept of a typical ASP.NET development practice. Rather than populating a specific control via code, we may bind a control to a data source (something that contains data). In this case, the control will automatically assume the value or values contained in the data source. At this stage, you may not see the benefit of this approach, but it will shine like a jewel when we learn how to display and manipulate data from databases. In the example shown in Figure 3.36 and Figure 3.37, we have shown a similar example of binding an HtmlSelect control to a SortedList). Since the ArrayList object is also very common in ASP.NET framework, we will bind our ListControl to an ArrayList in our next example.

Often we create and load a collection of objects into certain structures.These structures are known as collection objects. For example, an ArrayList is a collection object. It is actually very similar to a dynamic array of objects. Suppose that one of these ArrayList objects contains the names of some flowers. If needed, we may bind one or more controls to this ArrayList.That way, the controls will be automatically loaded with the values in the ArrayList. Don’t worry! We will not deprive you of binding controls to databases.Those examples will appear later in this chapter.

Binding a control to a data source is very simple. Rather than developing a data loading procedure, we just set the DataSource property of a control to a data source.Then we employ the DataBind() method of the control to accomplish the binding task. In our example, we will first create an ArrayList of flowers, and then we will bind a list box (lstFlower) with the ArrayList. Figure 3.48 shows the runtime view of the application.The complete listing of the code is shown in Figure 3.49 (also available in the accompanying CD in a file named DataBind1.aspx).

www.syngress.com

112 Chapter 3 • ASP Server Controls

Figure 3.48 Binding a ListControl to an ArrayList

Figure 3.49 Complete Listing of DataBind1.aspx

<!— Chapter3\DataBind1.aspx —>

<%@ Page Language="VB" Debug="true" %> <html><head></head><title></title><body> <form runat="server">

Select a flower, and then click the submit button please:<br> <asp:ListBox id="lstFlowers" runat="server" rows="3"

AutoPostBack="True" onSelectedIndexChanged="showSelection"/> </asp:ListBox><br><br>

<asp:Label id=lblMessage runat="server"></asp:Label></p> </body></form></html>

<script language=vb runat="server">

Sub Page_Load(source As Object, e As EventArgs)

If Not Page.IsPostBack Then

Dim myArrayList As New ArrayList

' Populate the ArrayList: This will be a data source myArrayList.Add("Azalea")

myArrayList.Add("Tulip")

myArrayList.Add("Rose")

' Step 1: Specify the Datasource property of the list control

lstFlowers.DataSource= myArrayList

'Step 2: Employ the DataBind() method to load the

'list control from its DataSource automatically

lstFlowers.DataBind()

lstFlowers.SelectedIndex=0

Continued

www.syngress.com

ASP Server Controls • Chapter 3

113

Figure 3.49 Continued

End If

End Sub

Sub showSelection(sender As Object, e As EventArgs)

lblMessage.Text="You have selected "+lstFlowers.SelectedItem.Text

End Sub

</script>

Validation Controls

A validation control enables us to validate an input and display an error message if necessary. It is very much like other server-side controls with certain additional methods and properties. First, the server treats it as an invisible control. After the user has entered erroneous data, it becomes visible. It is a powerful, rapid application development feature; however, a developer needs to understand its behavior and the methods thoroughly before he or she can appreciate it.There are certain rough edges in the Beta 2 version, which hopefully will be polished in the final product.The best strategy to learn the family of controls is to learn them one at a time, and finally to apply the summary validation.

Various types of validation controls are as follows:

RequiredFieldValidator Checks if the input control has any value.

RegularExpressionValidator Checks the value against a regular expression (pattern).

CompareValidator Checks if the value is acceptable compared to a given value or compared to the content of another control.

RangeValidator Checks if the input control’s value is within a specified range.

CustomValidator Allows you to develop custom validation.

ValidationSummary Reports a summary of all errors.

By default, each of the validation controls performs the validation task at the client-side as well as at the server-side. Except for the RequiredFieldValidator, all other validation controls treat an empty field as a valid field.Therefore, we will need to apply a RequiredFieldValidator to every input field that we want to validate.You can attach more than one validation control to an input. For example,

www.syngress.com

114 Chapter 3 • ASP Server Controls

we may use a RequiredFieldValidator and a RangeValidator to ensure that an input is not empty and falls within a specified range.

There are a number of common properties in these controls.The major ones are:

ErrorMessage In case of an error, the system displays this message at

the location of the control, and in the summary report, if any.

Display A validation control is kept invisible until a bad input is entered. In case of a bad input, the system has to display the error message.The display mechanism can be handled in one of three ways.

Display= “static” Initially, enough room in the page is reserved for the expected error message.

Display= “dynamic” No room is initially reserved. In case of an error, the message is displayed by displacing existing contents of the page.

Display=“none” The message won’t be displayed at the location of the control; however, it will be reported in the summary report, if any.

The RequiredFieldValidator Control

In the following example, the user is expected to enter two values. If he or she skips any one of the values and clicks the Submit button, the system will report the error. Please notice that we do not require any extra code for performing this validation.When the Submit button is clicked, the form will be sent to the server, and the server will do the automatic validation.The run-time view of this application is shown in Figure 3.50.The code for this application, as shown in Figure 3.51, is self-explanatory and is also available in the accompanying CD in a file named Validator1.aspx.

Figure 3.50 Using the RequiredFieldValidator Control

www.syngress.com

ASP Server Controls • Chapter 3

115

Figure 3.51 Validator1.aspx

<!—- Chapter3\Validator1.aspx —> <!— Required Field Validator —> <html><head</head>

<title>Example on Required Field validator</title><body> <form runat="server"><br> Enter Your Name:

<asp:TextBox id="txtName" rows="1 " width="50" runat="server"/>

<asp:RequiredFieldValidator id="validTxtName"

runat="server" controlToValidate="txtName"

errorMessage="Name must be entered" display="static">

</asp:RequiredFieldValidator></br>

Hours worked?

<asp:TextBox id="txtH" width ="30" runat="server" />

<asp:RequiredFieldValidator id="validTxtH" runat="server"

controlToValidate="txtH" errorMessage="Hours must be entered"

display="static">

</asp:RequiredFieldValidator></br>

<asp:Button id="btnSubmit" runat="server" text="Submit" />

</form></body></html>

The RegularExpressionValidator Control

The RegularExpressionValidator control is typically used to match an input pattern. As an example, let us assume that the value of hours-worked field must have one to three digits. In this case, we will add a RegularExpressionValidator to the txtH control. In the RegularExpression property of the RegularExpressionValidator, we will specify a pattern /d{1,3}. This will force the system to raise an error if the user input is not one-to-three digits long.The output of this application is shown in Figure 3.52.The code for this example is shown in Figure 3.53 and is also available on the accompanying CD in a file named Validator2.aspx.

www.syngress.com

116 Chapter 3 • ASP Server Controls

Figure 3.52 Using RegularExpressionValidator Controls

Figure 3.53 Validator2.aspx

<!—- Chapter3\Validator2.aspx —>

<%@ Page Language="VB" Debug="true" %> <html><head</head><body>

<form runat="server"><br> Enter Your Name:

<asp:TextBox id="txtName" rows="1 " width="60" runat="server"/> <asp:RequiredFieldValidator id="validTxtName" runat="server"

controlToValidate="txtName" errorMessage="Name must be entered" display="static">

</asp:RequiredFieldValidator></br> Hours worked?

<asp:TextBox id="txtH" width ="40" runat="server" /> <asp:RequiredFieldValidator id="validTxtH" runat="server"

controlToValidate="txtH" errorMessage="Hours must be entered" display="static">

</asp:RequiredFieldValidator>

<asp:RegularExpressionValidator id="regvH"

runat="server" display="static" controlToValidate="txtH"

errorMessage="Hours must be 1-3 digits only"

validationExpression="\d{1,3}">

</asp:RegularExpressionValidator></br>

<asp:Button id="btnSubmit" runat="server" text="Submit" />

</form></body></html>

www.syngress.com

ASP Server Controls • Chapter 3

117

NOTE

The details of regular expressions can be found in any Perl book. You may also review http://msdn.microsoft.com/scripting/default.htm?/ scripting/JScript/doc/jsobjregexpression.htm.

We have found the following source to be adequate: www.microsoft.com/mind/defaulttop.asp?page=/mind/1098/jscript/ jscript.htm&nav=/mind/1098/inthisissuecolumns1098.htm.

The CompareValidator Control

The CompareValidator control compares an input to a specified value or to the value of another control.You can also use it to check if the input is of any particular data type. In our next example, we will add a textbox named txtR. In this textbox, the user will enter the hourly rate. Suppose that we want the data-type of this field to be Double.We will apply a CompareValidator control to test the data-type of the txtR. Note that if the data entered is convertible to the desired data-type, the validation will succeed.The run-time view of the application is shown in Figure 3.54.

Figure 3.54 Using the CompareValidator Control

We have added the code following code to accomplish this objective (you may review the complete code in the file named Validator3.aspx on the CD). Please notice that we have set the type property to “Double,” and the operator property to “DataTypeCheck.”

<asp:CompareValidator id="comvR" runat="server" display="static"

controlToValidate="txtR" errorMessage="Rate must be numeric"

type="Double" operator="DataTypeCheck">

</asp:CompareValidator></br>

www.syngress.com

118 Chapter 3 • ASP Server Controls

In the type property of the CompareValidator, we may specify: String, Integer, Double, DateTime, and Currency. In the operator property, we may specify: Equal, NotEqual, GreaterThan, LessThan, GreaterThanEqual, LessThanEqual, and DataTypeCheck.

The RangeValidator Control

You can use this control to check if an input is within an acceptable range. Suppose that we want to provide a textbox for collecting data on “number of dependents.”We want to enforce a constraint that this field should be from 0 to 10. Figure 3.55 illustrates the use of a RangeValidator in this particular situation.

Figure 3.55 Using the RangeValidator Control

In our code, we have used the type, minimumValue, and maximumValue properties of a RangeValidator to apply the constraint.We have applied the RangeValidator as follows: (The complete code is available in Validator4.aspx.)

<asp:RangeValidator id="ranvDependents" runat="server"

display="static" controlToValidate="txtDependents"

errorMessage="Must be from 0 to 10"

type="Integer" minimumValue=0 maximumValue=10>

</asp:RangeValidator></br>

The CustomValidator Control

In many situations, we may not be able to use the existing validators to validate a complex rule. In that case, we may apply a CustomValidator. When applying a CustomValidator, we may provide our own functions that will return true or false. We may develop the code for server-side validation only, or we may develop the code for server-side as well as the client-side validation. Suppose that the user will enter the data about his or her department number. Also suppose that the

www.syngress.com

ASP Server Controls • Chapter 3

119

department number must be evenly divisible by 10.We will develop a simple custom validator to enforce this rule at the server-side.The run-time display of this application is shown in Figure 3.56.

Figure 3.56 Using the CustomValidator Control

We have developed a VB function named validateDeptNum to perform the check.We have also specified its name in the onServerValidate property of the CustomValidator control. An excerpt from the complete code for this application is shown in Figure 3.57.The complete code is available on the CD in the file named Validator5.aspx.

Figure 3.57 The Code for CustomValidator (Validator5.aspx)

What is your Department Number?

<asp:TextBox id="txtDeptNum" width ="40" runat="server" /> <asp:CustomValidator id="cusvDeptNum" runat="server"

display="static" controlToValidate="txtDeptNum" onServerValidate="validateDeptNum" errorMessage="Must be in multiples of 10" >

</asp:CustomValidator></br>

<asp:Button id="btnSubmit" runat="server" text="Submit" /> </form></body></html>

<script language="VB" runat="server">

Sub validateDeptNum(source As Object, s as ServerValidateEventArgs) If (CInt(s.Value) Mod 10)=0 Then

s.IsValid= True Else

Continued

www.syngress.com