![]() |
|||
| |
|||
More applications today are being written as browser-based applications. Before Visual Basic .NET, it was difficult to create these browser-based applications using Visual Basic. With Visual Basic .NET, these become as easy to create as traditional Windows-based applications. Today, you will look at how you can create browser-based user interfaces. The tools within Visual Basic .NET assist the developer in creating Web pages that provide fairly rich user interfaces across any browser type. In particular, today's lesson will focus on
How the Web programming model differs from the traditional Windows-based model
Using standard Web Forms controls
Using advanced Web Forms controls
Using the Validator controls
Some days, I think that everyone in the world is on the Internet, especially when my access speed is in the painfully slow mode because everyone is browsing, chatting, and e-mailing (but not doing business). (As a tip, I somehow find that the best time to be online is during Star Trekprobably just a coincidence.) Obviously, one of the most important, or at least popular, aspects of the Internet is the World Wide Web (WWW or just Web). However, there has generally been a shortage of really good programming tools for creating Web "programs," rather than just simple Web pages. This is at least partly because creating applications for the Web is different from creating applications for a desktop computer, with which you have more control. In addition, Web applications must deal with the network more frequently.
So, what is the "Web Programming model"? It is just a term used to describe how you can design, or architect, a program that uses Web pages in a browser to allow the user to enter information. These Web pages are designed using HTML (HyperText Markup Language).This book won't be covering HTML, but there are plenty of books on the market that do.
A browser is an application that knows how to read HTML and display it on the screen. Usually (but not always), most of the work of an application is done on the Web Server. The Web Server is another program running on a computer that knows how to return HTML on demand. In Windows NT and 2000, this program is called Internet Information Server (IIS). The information is carried between the browser and the server using a protocol, or language, called HTTP (Hypertext Transfer Protocol).
Note
The actual name of IIS has changed with the different versions. In Windows NT 4.0 Server, it is called Internet Information Server. In Windows 2000, it is called Internet Information Services, whereas in Windows NT 4.0 Professional, it is Personal Web Server.
In the "beginning" of the World Wide Web, Web pages were static. That is, they never really changed. Things got more interesting when people started to create dynamic, or changing, Web pages. This was the dawn of the Web program. With Web programs, rather than simply returning the same HTML every time, the Web server can perform some task and return HTML appropriate to the result. For example, the user might request the sales information for a particular date range. This information is passed to the server. The server, in turn, might look up that information in a database and then write the HTML to display it to the user. The whole process looks similar to Figure 10.1.
Figure 10.1
Web programming model.
Alternatively, the server (or Web page designer) might add programming information to the page itself, creating a page that is a little program in its own right. This is often called Dynamic HTML (or DHTML). With DHTML, the page includes some JavaScript (a programming language, like Visual Basic .NET that runs in Web pages) or other language. The code can run in the browser without needing to send any information back to the server. Figure 10.2 shows this model in action.
Figure 10.2
Dynamic HTML programming model.
There are a variety of techniques that can be used to create a Web program. Some of the most common techniques used in the past have been ASP (Active Server Pages), Perl (another programming language), or JSP (Java Server Pages). The technique used by Web Forms is an improvement of ASP, ASP.NET.
ASP.NET is Microsoft's name for its improved version of ASP. Although ASP was an easy method for building dynamic Web pages, it had some problems that ASP.NET solves:
ASP often required too much code to get something done. ASP.NET requires less code (often much less code) for common programming tasks.
ASP still suffered from the limited number of controls that HTML suffers from. ASP.NET adds the idea of "server-side controls" that can generate HTML appropriate to the browser requesting them. Although these controls are just HTML in the browser, they can represent a great deal of HTML and code, saving you from having to write it.
ASP only allowed programming in a language such as VBScript. VBScript is interpreted at runtime, not compiled as real Visual Basic is. ASP.NET allows you to write Web pages in real, fully compiled Visual Basic .NET.
ASP.NET is also designed to solve other problems with ASP that aren't appropriate to this discussion of building user interfaces, such as improvements in scalability and memory use.
When you are designing a Web-based program using Web Forms, there are a number of differences you must keep in mind. Some of the differences include
Web-based applications tend to have more code on the server, rather than on the client. That is, the look and feel of your program comes from the browser, but the "smarts" are on the server.
Web-based applications are dependent on the capabilities of the browser used to view them. Sadly, each browser has different capabilities, and many Web developers have had to struggle with these differences as they designed their programs.
When you receive a Web page, it tends to be static. Although there are ways you can update the page without returning to the server (that is, to make it dynamic), these methods make creating the page more complex. Therefore, producing animated forms (or any kind of response to the user) is more difficult with Web-based applications.
Many operations of a Web-based application require a "network round-trip". This is because of the separation of code and design. In order to have a button or other control do something, it is often necessary to send information to the server. The server then responds appropriately. You should keep this in mind when you are creating Web applications. This back-and-forth communication might take a while, so you should only do it as necessary.
Web-based applications are limited, both by the limitations on the browser itself, and on the number of browsers available on the market. Browsers are limited in the types of controls that can be used, as well as by their limited drawing capabilitiesthat is, you typically can't draw on the Web page. In addition, if the user has installed an older version of a browser, or has disabled certain features, the Web page can react in different ways. This is one of the main reasons that Web-based applications tend to place most of the code on the server. In addition, this has meant that traditionally Web-based applications have required a lot of code to be added to change the appearance of the Web page based on the browser viewing it.
Fortunately, the Web Form controls hide most of those details from you. They are written to produce dynamic output (that is, the page can change without needing to send information back to the server) if the controls detect that the browser is capable of using dynamic output. If they do not recognize the browser being used, or if the browser does not support dynamic updating, only plain HTML is returned to the client browser. This ensures the developer that the client browser will receive the Web page designed, within the limitations of the browser.
In addition to the limits caused by the browser, Web-based applications also require the developer to consider the fact that the client and server are separated, possibly by great distances by a network. This means that operations that might only take a few seconds if the client and server were close (or even the same machine) could take a long time. So, operations like animations might be jerky, or not display at all until the download is completed. Also, the speed of the connection comes into play. If you are accessing the Web page using a slower modem, this difference is made even more significant.
With all these issues to keep in mind, you might ask "Why bother creating Web applications?" Although there is a downside to creating Web applications, there are many benefits:
Installation To make your application available, all you need to do is point someone at the URL. The application is immediately usable by the client. This saves you from having to visit each of those client machines, or from having your users all install the application.
New Versions and/or bug fixes When you want to upgrade to a newer version of part of your application, you only need to install the upgrades at the server, not at every client.
Performance Improving the performance of Web applications is much easier than improving the performance of regular applications. You can improve the performance of Web applications by adding more servers and distributing the requests across all the servers.
Knowledge If you already know some HTML, Web applications can be much easier to create than Windows applications. Alternatively, they can be easier to learn, if you know neither HTML nor Windows.
So, when designing an application, should you create a Windows-based or Web-based program? The easy (but unsatisfying) answer is, "It depends." Many applications fit either type, but people are starting to create more Web-based applications. The capability to easily make upgrades and fixes available is compelling, so you might want to at least consider creating your programs as Web applications first.
Some applications are not candidates for Web applications, however. Any programs that require a continuous link between client and server are not appropriate, nor are applications that require a lot of graphics (such as games). Finally, if you only have a single computer involved (that is, not a client/server application like a database program), or if the app is only for yourself, it might make sense to create a Windows-based application.
Designing a Web page using Visual Basic .NET is similar to designing a normal Visual Basic .NET application. The only difference is what happens behind the scenes. Rather than code being added to create the controls and set their properties, HTML tags are added to the ASP.NET page, and code is added to a Visual Basic .NET file that works behind the scenes.
The controls available to you in creating a Web application are similar to those available in Windows applications. They include all the common controls you're used to using (see Figure 10.3). Table 10.1 describes these controls in brief.
Figure 10.3
Standard controls for Web Forms.
|
Control |
Description |
|
Label |
Use to place text on the Web Form. Alternatively, you can simply click on the Web Form and start typing. The Label gives you better control over formatting, and allows you to place the text where you want it. Finally, the Label control also allows you to dynamically change the contents inside of your application, something not possible with text added to the form. |
|
TextBox |
Use to give the user a field to enter information into. This will often be the most common control added for a Web application. |
|
Button |
Use to give the user something to click to carry out some action. |
|
LinkButton |
Similar in action to the normal Button control, the LinkButton is something for your Web application's users to click. The difference is that the Button looks like a button, whereas the LinkButton is a hyperlink. (That is, the user sees a nice blue, underlined pointer somewhere.) |
|
ImageButton |
Similar in action to the normal Button control, the ImageButton is something for your users to click to perform some action. The difference is that the ImageButton is a graphic that your users can click. |
|
Hyperlink |
This is similar to the LinkButton, except that the LinkButton has a Click event, whereas the Hyperlink does not. This means that you can write code only to deal with LinkButton clicks, whereas the Hyperlink can be used only to send the user elsewhere. |
|
DropDownList |
DropDownList controls are quite common in Web Forms. They are a list that initially only takes a single line. You can click on the drop-down arrow to open them and see the full list. When you select an item from the list, the list again closes, and only a single line is shown, containing your selection. You would use these controls when your user needs to select a single item from a list, and when you want to save screen spacefor example, when selecting a state or country code. |
|
ListBox |
ListBox controls allow the user to select one or more items from a list of choices. They differ from DropDownLists in that the list is always visible. One other difference is that it is possible to select multiple items in a ListBox. Use the ListBox when you need this multiple selection capability (although see CheckBoxList), when you want the user to always see the choices, or when screen space is plentiful. |
|
CheckBox |
The CheckBox represents the answer to a yes or no question. It is either checked, or unchecked, and therefore is used when you want the user either to select an option or not. It differs from the RadioButton, in that the CheckBox is independent of other CheckBox controls, whereas the RadioButton is generally one possible option out of many. |
|
CheckBoxList |
The CheckBoxList is a series of CheckBox controls. Each one is independent of the others, but the CheckBoxList control is a handy way of adding a number of CheckBox controls to a page. This control is especially useful if you have a collection of items (perhaps retrieved from a database) from which you want the user to select. The CheckBoxList is also a handy replacement for the ListBox when you want the user to select a number of items. However, you should still use the ListBox if you have more than about six items. |
|
RadioButton |
The RadioButton is similar to the CheckBox in that its value is either True or False. It differs from the CheckBox in that RadioButton controls tend to "travel in packs." Although each CheckBox on a form can be set independently to either True or False, only one RadioButton in a set can be True. So, you can think of a CheckBox as posing a Yes/No question, whereas a RadioButton (or rather a group of RadioButtons) is more like a multiple-choice question to which only one answer is correct. |
|
RadioButtonList |
The RadioButtonList is a group of RadioButton controls. It makes creating this group easy, if you already have a list from some other location (like a database). |
|
Image |
The Image control allows you to place a graphic on the page. |
|
Panel |
The Panel control is similar to the Label control in that it is just a placeholder for text. The difference is that the Panel control can hold other controls. As such, it is a great control to use when you need to separate or highlight information or controls. Similar, or related, controls can be grouped in a Panel control to make them stand out from the other controls. |
Just as with Windows controls, you use the Web Form controls by double-clicking them in the toolbox, or by dragging them onto your form. In this case, however, the form is a Web page.
Let's create a simple Web Form application to see how these controls make it easy to write Web programs.
Start the development environment if it is not running and create a new Web application. Call this one Madlib. You'll use it to create a simple Web application to see many of the standard controls in action. Select File, New, Project to open the New Project dialog. Open the Visual Basic Projects folder and select the Web Application project template. Change the name of the project to Madlib and click OK to build the project.
Note
Before you create a Web application, you should first install or have access to Internet Information Services (or Internet Information Server).
Just as with Windows-based applications, your first step is to lay out the controls you will be using in your application (see Figure 10.4 for the final result). You'll start by adding a graphic to your page.
Figure 10.4
Madlib form.
Drag an Image control onto the form. Initially, it should look like a blank square (or rather a missing graphic) because you need to set the path to the graphic. Go to the property window and find the ImageUrl property. When you click in the Property window for the ImageUrl property, you should see a button with three dots appear. Just as with Windows applications, this means that a dialog will help you set this property. Click the button, and find a nice graphic. (I created one that said Madlib in the Paint program that comes with Windows 2000.) Click OK, and the graphic should now be showing on the form.
Explaining your program is generally considered good form. Add a Label control and add a simple explanation to the Text property. The text I entered was
A Mad Lib is a game where one player selects a series of words (usually by type of word, or a description). These words are then plugged into a story at specific spots to create a (hopefully) amusing, personalized end result.
Next, you'll add the controls to the page for the various items you'll plug in. Table 10.2 describes the controls and property settings used.
|
Control |
Property |
Value |
|
Label |
(ID) |
lblName |
|
|
Text |
Your first name: |
|
|
Font Bold |
True |
|
TextBox |
(ID) |
txtName |
|
Label |
(ID) |
lblDate |
|
|
Text |
A date: |
|
|
Font Bold |
True |
|
TextBox |
(ID) |
txtDate |
|
Label |
(ID) |
lblFruit |
|
|
Text |
A kind of fruit: |
|
|
Font Bold |
True |
|
DropDownList |
(ID) |
cboFruit |
|
|
Items |
The DropDownList has a dialog that assists you in adding items to it. Click the Items property, and then the resulting Build button. See Figure 10.5 for the resulting dialog. Add a number of fruits, by clicking the Add button, and then set the Text property. Repeat for about 10 items. I added Mango, Orange, Banana, Currant, Berry, Kumquat, Peach, Kiwi, Apricot, and Plum. |
|
Label |
(ID) |
lblNumber |
|
|
Text |
A number from 100 to 1000: |
|
|
Font Bold |
True |
|
TextBox |
(ID) |
txtNumber |
|
|
Text |
500 |
|
Label |
(ID) |
lblEmotion |
|
|
Text |
An emotional state: |
|
|
Font Bold |
True |
|
RadioButtonList |
(ID) |
rlstEmotion |
|
|
Items |
The Items property of the RadioButtonList is similar to the Items property of the DropDownList, and has the same editor. Add a few of your favorite emotional states here. I added Excited, Frustrated, Intrigued, Saddened, Panicky, Ecstatic, Angry, Jealous, Frightened, Happy, Shocked, and Blue. |
|
|
RepeatColumns |
3 |
|
Label |
(ID) |
lblVerb |
|
|
Text |
A verb: |
|
|
Font Bold |
True |
|
TextBox |
(ID) |
txtVerb |
|
Label |
(ID) |
lblOccupation |
|
|
Text |
An occupation: |
|
|
Font Bold |
True |
|
TextBox |
(ID) |
txtOccupation |
|
Button |
(ID) |
cmdWrite |
|
|
Text |
Write Story |
|
Button |
ID |
cmdClear |
|
|
Text |
Clear |
|
Label |
(ID) |
lblResult |
|
|
Text |
Leave this field blank (that is, clear out the value in the Text property) |
|
|
BorderStyle |
Groove |
|
|
Width |
75% |
In addition, you might want to start a new line periodically to arrange the controls better on the page. See Figure 10.5 for one example. If you're familiar with HTML, you might want to put the controls in a table for even better formatting possibilities.
Note
There is another technique you can use to put controls on a Web Form. If you look at the properties of the Web Form (look for the DOCUMENT in the drop-down list of objects at the top of the Property window), you will see one called pageLayout. By default, this is LinearLayout. The alternative, GridLayout can help you create rich Web Forms. If the pageLayout is set to GridLayout, you can place controls on the Web Form just as you can on a Windows Form.
Figure 10.5
Adding items to the DropDownList.
Most of the properties used should make sense; however a few likely need extra explanation. Many controls that work with lists are able to be "bound" to a collection of items. Often, this means that they can be attached to information retrieved from a database, however, they can also be attached to other collections, such as arrays. Controls capable of this can be identified easily, as they have an Items collection. This Items collection appears in the Property window, and allows you to add items without binding the control to an array or other collection. This is the easiest way to add the items if they will not be changing. If they will likely change, you should keep them in a database and retrieve them at runtime, then bind them to the control. You will see this in action in Day 12, "Accessing Data with ADO."
The RadioButtonList has a relatively rare property: RepeatColumns. You can set this to control the number of columns used to display the list of items. This can be a great way to save some space on the screen, while still showing all the items. Behind the scenes, the RadioButtonList writes HTML to make this work. This is one of the features that make these controls easier to use than writing your own HTML.
Your next step in writing your Web application is to add code. You will only be adding code to the two buttons. You'll start with the Clear button. This button will clear the information in the various TextBox controls, and in the results Label. Double-click on the Clear button and add the code shown in Listing 10.1.
1 Private Sub cmdClear_Click( _ 2 ByVal sender As System.Object, _ 3 ByVal e As System.EventArgs) _ 4 Handles cmdClear.Click 5 txtName.Text = "" 6 txtDate.Text = "" 7 txtVerb.Text = "" 8 txtNumber.Text = "" 9 txtOccupation.Text = "" 10 lblResult.Text = "" 11 End Sub
The code for this button is simple. All it does is sets the Text property of all the TextBox controls and the results Label to "". This clears those controls.
The code in Listing 10.2 also is simple. The basic idea is that you build a long string containing the entire story, and this is written to the results Label.
1 Private Sub cmdWrite_Click( _ 2 ByVal sender As System.Object, _ 3 ByVal e As System.EventArgs) _ 4 Handles cmdWrite.Click 5 'here's were we combine the selections 6 'the user has made into the final story 7 Dim sTemp As String 8 sTemp = "Diary of " & txtName.Text & _ 9 " for " & DateTime.Today.ToString & "<br>" 10 sTemp &= "On " & txtDate.Text & _ 11 " I started to program in Visual Basic.NET. " 12 sTemp &= "I'm " & rlstEmotion.SelectedItem.Text & "! " 13 sTemp &= "I think I'm going to go out and " & txtVerb.Text 14 sTemp &= " my new " & txtNumber.Text 15 sTemp &= " PicoHertz " & cboFruit.SelectedItem.Text 16 sTemp &= " and become a " & txtOccupation.Text & "." 17 'the final story goes into the Label control 18 lblResult.Text = sTemp 19 End Sub
The process begins on line 7, where you declare the string. The string is then built through lines 816, and the result is put into the Text property of the lblResult control on line 18. One symbol that likely seems strange is the &= that appears on lines 1016. A new feature of Visual Basic .NET, this is a shortcut when adding to a string. The code on lines 10 and 11, for example,
10 sTemp &= "On " & txtDate.Text & _ 11 " I started to program in Visual Basic.NET. "
is equivalent to:
10 sTemp = sTemp & "On " & txtDate.Text & _ 11 " I started to program in Visual Basic.NET. "
You can use the &= operator to make your code shorter when you are adding more information to the end of an existing string.
After you have added the code, you're ready to build and experiment with this program. Select Build from the Build menu and then run the program. This should start a browser and load your page. Enter a few items and click the Write Story button to see your story. Figure 10.6 shows the Web Form in action.
Figure 10.6
Madlib form in action.
Although it is easy to build a form with controls that are available as part of HTML, Web Forms become even more useful (and colorful, and easy to use) when you apply some of the more advanced controls, such as the Calendar, AdRotator, or Data controls. Although they are built using more simple controls, they make building user interfaces easier.
The Calendar control shows, strangely enough, a monthly calendar. This control allows the user to view and select dates more easily than by using a TextBox. In addition, by using the Calendar, you reduce the chance of the user entering a date in an invalid format. The Calendar control has a huge number of properties, however, most of them affect how the Calendar control is displayed. Just about everything visible on the control can be adjustedthe colors, whether the weekday or month names are abbreviated, and so on. Table 10.3 outlines a couple of the most useful properties of the Calendar control.
|
Item |
Property |
Description |
|
SelectedDate |
Property |
The date that will be returned by this control. |
|
VisibleDate |
Property |
The date showing in the control. Although this is generally the same as the SelectedDate, it might be different, particularly if you are trying to set the date through code. |
Let's update the Madlib project to use a Calendar control instead of the TextBox for the date entered. You can either edit the old form, or create a copy if you want to view both.
Delete the Date text box and add a Calendar control. At this point, you have the choice of either playing with the properties that affect the appearance of the Calendar, or being lazy and selecting the AutoFormat link that appears at the bottom of the Properties window when you select the Calendar control. I clicked the link and selected Colorful 2. (Why fuss and make something ugly when a professional already has made something look goodone of my programming strategies?) Set the Calendar's Name property to calDate.
You will also need to change the code from Listings 10.1 and 10.2 slightly because of the change in the name of the control. Listings 10.3 and 10.4 show the new, changed code.
1 Private Sub cmdClear_Click( _ 2 ByVal sender As System.Object, _ 3 ByVal e As System.EventArgs) _ 4 Handles cmdClear.Click 5 txtName.Text = "" 6 calDate.SelectedDate = DateTime.Today 7 txtVerb.Text = "" 8 txtNumber.Text = "" 9 txtOccupation.Text = "" 10 lblResult.Text = "" 11 End Sub
Only a single line of code is changed. Because you no longer have the TextBox txtDate, you cannot set it to "". Instead, you can reset the Calendar to select today (DateTime.Today), as you do in line 6.
1 Private Sub cmdWrite_Click( _ 2 ByVal sender As System.Object, _ 3 ByVal e As System.EventArgs) _ 4 Handles cmdWrite.Click 5 'here's were we combine the selections 6 'the user has made into the final story 7 Dim sTemp As String 8 sTemp = "Diary of " & txtName.Text & _ 9 " for " & DateTime.Today.ToString & "<br>" 10 sTemp &= "On " & calDate.SelectedDate & _ 11 " I started to program in Visual Basic.NET. " 12 sTemp &= "I'm " & rlstEmotion.SelectedItem.Text & "! " 13 sTemp &= "I think I'm going to go out and " & txtVerb.Text 14 sTemp &= " my new " & txtNumber.Text 15 sTemp &= " PicoHertz " & cboFruit.SelectedItem.Text 16 sTemp &= " and become a " & txtOccupation.Text & "." 17 'the final story goes into the Label control 18 lblResult.Text = sTemp 19 End Sub
Again, the only change in Listing 10.4 is on line 10. Rather than retrieving the date in the TextBox, the code retrieves the selected date from the Calendar with calDate.SelectedDate.
Doesn't this property thing make sense? That's why they didn't call it Visual Complex .NET.
When you are writing data entry forms for the Web, you often need to make certain that the form is filled out correctly. This could mean that certain fields are filled in, or that some fields are filled in, but with values that fit into a range. In the past, this could be done by writing code at either the server or the client. If the code is at the server, it might cause the information to be passed between the client and server needlessly. If you would rather place the code at the client, you run into the problem with cross-browser incapability.
A number of Validator controls come with Visual Basic .NET that make form validation much easier. The controls will either process the validation at the server, or at the client if the control determines that the browser is capable of it. Five validation controls are available in Visual Basic .NET:
RequiredFieldValidator Ensures that a field has been filled in. You can use it any time that you want to make certain that the user completes a form before submitting it.
CompareValidator Ensures either that two fields match, or that a field is compared to some value. In the first case, matching fields is useful when you want the user to enter his password twice. Comparing a field to some value is useful if you wanted the user to enter a positive number, or if the user's entry must be a particular type of information (for example, a date).
RangeValidator Ensures that the value entered in a field is within a range. The range could be between two values (for example, a starting and ending date), or two controls. For example, you might have one control where the user enters a minimum value, and a second for the maximum value. The Validator would then ensure that the value entered in a third control was between these two values. This is useful as part of a report, in which you might want the user to select a date that is within the range of information stored in a database.
RegularExpressionValidator Ensures that the value entered "looks" like it should. The value is compared to a Regular Expression. If it matches, the value is considered valid. This can be useful for values that must have a certain structure, such as phone numbers, ISBNs, or part numbers.
CustomValidator Allows you to add your own code to validate the field. The most flexible of the validators, this code could run either at the server or on the client. This would be useful when one of the other validators does not fit your purpose, or valid information must be determined through some processfor example, if the value must be one of a number of entries that are in a database.
In addition to these five controls, there is also the ValidationSummary control, which displays all the error messages from all the Validator controls on the same page. This is useful to provide a single location for all this information.
The five validation controls have a number of important properties in common. These relate to the control they monitor, and how the error is displayed. The most important of these properties are described in Table 10.4.
|
Property |
Description |
|
ControlToValidate |
This is the most important property of all the validation controls. It should be set to point to another control (by name) on the same form. This is the control that will be monitored by the validator. Use the drop-down in the Property window to select the monitored control. |
|
ErrorMessage |
This is the message to display if there is an error with the validator, for example, if the field is left blank. This should be enough information to allow the user to determine what is wrong, and how to fix the error. |
|
Display |
This is a rather odd property that defines how the Validator control appears on the Web page. By default, it is Static; however, there are two other choices, Dynamic or None. If the value is Static, the space taken up by the ErrorMessage will always be taken up, even if the ErrorMessage is not being shown. This is useful if you want to guarantee how your Web page will be laid out. Dynamic means that the control takes up no space until the ErrorMessage property is shown. This is useful if you don't want blank spaces on your form. Finally, if this property is set to None, the ErrorMessage will never be shown. This is really only useful in conjunction with the ValidationSummary control (which will show the error). |
You can use some of these controls to finish the Madlib sample application. You can use the RequiredFieldValidator control to ensure that the user has entered information in certain fields, and the RangeValidator to make certain that an appropriate number has been entered in the txtNumber field. Finally, you can summarize all errors with a ValidationSummary control.
Again, either copy the old project or form, or open the existing project to edit it. You'll add the Validator controls to this existing form.
Drag a RequiredFieldValidator next to each of the remaining TextBox controls (txtName, txtNumber, txtVerb and txtOccupation). Add a RangeValidator next to the RequiredFieldValidator you added to the txtNumber field. Finally, add a ValidationSummary control on a line of its own between the buttons and the lblResult control. Set the properties of each of these controls as shown in Table 10.5.
|
Control |
Property |
Value |
|
RequiredFieldValidator |
ID |
reqName |
|
|
ControlToValidate |
txtName |
|
|
ErrorMessage |
Please enter a name |
|
RequiredFieldValidator |
(ID) |
reqNumber |
|
|
ControlToValidate |
txtNumber |
|
|
ErrorMessage |
Please enter a number |
|
|
Display |
Dynamic |
|
RangeValidator |
(ID) |
rngNumber |
|
|
ControlToValidate |
txtNumber |
|
|
ErrorMessage |
Please enter a number from 100 and 1000 |
|
|
Display |
Dynamic |
|
|
Type |
Integer |
|
|
MaximumValue |
1000 |
|
|
MinimumValue |
100 |
|
RequiredFieldValidator |
(ID) |
reqVerb |
|
|
ControlToValidate |
txtVerb |
|
|
ErrorMessage |
Please enter a verb |
|
|
Display |
Dynamic |
|
RequiredFieldValidator |
(ID) |
reqOccupation |
|
|
ControlToValidate |
txtOccupation |
|
|
ErrorMessage |
Please enter an occupation |
|
|
Display |
Dynamic |
|
ValidationSummary |
(ID) |
valSummary |
You should take a moment to describe the three properties of the RangeValidator you haven't assigned previously. Although the MaximumValue and MinimumValue should make sense in terms of something called a RangeValidator, the Type property is not so obvious. Because the RangeValidator might be used to test a number of different types of values (such as integers, financial values, or dates), the Type property identifies the type of information to compare. It can have one of the following values:
String The default, this causes the control to test whether the value is alphabetically between the two extremes.
Integer Compares the value to the two extremes to make certain that the value fits. Only Integer (whole) values are used.
Double The same as with Integer but includes the decimal part of the value and extremes.
Currency The same as with Integer but includes the first four decimals of the value.
Date Compares the values as though they were dates, so a value of August 27, 1964, would be allowed with a range between November 23, 1963, and April 1, 1986.
Now on to why the Validator controls are so useful. To make them work, you don't have to add any additional code. Build and view the new Web page (see Figure 10.7). Try leaving some fields blank, and delete the 500 that is the default value for the number field. You should see red error messages appearing on the form. If not, try clicking the Write Story button. You should see something like the form that appears in Figure 10.8. Try entering a value outside of the range for the number field. Finally, enter in correct values for all the fields and select the Write Story button. All error messages should go away, and our story should be written.
Figure 10.7
Madlib form showing validation controls.
Figure 10.8
Madlib form showing validation errors.
Web applications are becoming more and more important as time goes on, and Web Forms make creating them incredibly easy. They enable you to use the same techniques that you would use to build a desktop application to build a Web application that would work in any Web browser. By moving the code back to the server (that you can control), you get the best of both worlds that Web developers have striven fora rich user interface and cross-browser capabilities.
Although simply re-creating a Windows-like experience would be good enough for most, Web Forms go one step further, helping you more easily create validation routines and complex controls.
Tomorrow, you will start examining object-oriented programming. You will look at what OOP has to do with Visual Basic .NET, and with programming in general. You will see that you have been looking at objects all along, in the form of the .NET Framework, as well as the forms and controls you have been using.
Do I need to have a Web server available to use Web Forms?
Yes, Web applications need a Web server that knows about ASP.NET, such as Internet Information Server (IIS). IIS comes with a free Web server that is part of Windows NT Server or Windows 2000 Server.
Can I use Windows 98 or Windows Me to create and deploy Web applications?
These operating systems either come with, or have available, Personal Web Server (PWS). You cannot use PWS to create Web applications. Windows 9x can be used for creating Web applications, but are not great platforms for deploying them. You must create Web applications using IIS on either Windows NT 4 Server or Windows 2000.
How can I learn more about writing HTML?
Although Web Forms make knowing HTML almost optional, having a good working knowledge of HTML will help. Take a look at one of the fine books out on the market (Sams Teach Yourself HTML in 21 Days would be a good start) to learn more.
The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in Appendix A, "Answers to Quizzes/Exercises."
If you can simply add text to a Web page by typing, why do you need Label controls?
What controls help you to navigate between pages in a Web application?
How can I display graphics on a Web Form?
Create a registration application. This new Web application should allow the user to enter
His name. Must be filled in.
A username to use on your site (Alias). Must be filled in and no more than 10 characters long.
A new password (remember to keep the password a secret). The user should enter his password twice to make certain he has entered it correctly. Both fields must be filled in and match.
After the information has been entered, the user should click a button. The information will then be shown to the user.