How to Add Code and Validation Controls to a Form

Welcome to the fourth part of a five-part article series on building web applications with ASP.NET. In this part our form really starts taking shape, as we add validation controls -- something which belongs on every web-facing form. This article is excerpted from chapter two of Murach's ASP.NET 3.5 Web Programming with VB 2008, written by Anne Boehm (Murach, 2008; ISBN: 1890774472).

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 13
July 01, 2009
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

How to add validation controls to a form

A validation control is a type of ASP.NET control that’s used to validate input data. The topics that follow introduce you to the validation controls and show you how to use two of the commonly used controls. Then, in chapter 7, you can learn all the skills that you need to master the use of these controls.

An introduction to the validation controls

Figure 2-13 shows the Validation group in the Toolbox. It offers five controls that can be called validators. These are the controls that you use to check that the user has entered valid data. You can use the last control in this group, the validation summary control, to display all the errors that have been detected by the validators on the form.

The easiest way to add a validation control to a web form is to drag it from the Toolbox. In this example, four validators have been added to the form: two required field validators and two range validators. In this case, the controls have been added below the table so ASP.NET will use flow layout to position the controls. However, these controls could have been added to a third column of the table. Although these controls aren’t displayed when the form is displayed, the messages in their ErrorMessage properties are displayed if errors are detected.

In this case, the first required field validator checks to make sure that a value has been entered in the text box for the interest rate, and the first range validator checks to make sure that this value ranges from 1 to 20. Similarly, the second required field validator checks to make sure that a value has been entered in the text box for the number of years, and the second range validator checks to make sure that this value ranges from 1 to 45.

Validation tests are typically done on the client before the page is posted to the server. That way, a round trip to the server isn’t required to display error messages if any invalid data is detected.

In most cases, client-side validation is done when the focus leaves an input control that has validators associated with it. That can happen when the user presses the Tab key to move to the next control or clicks another control to move the focus to that control. Validation is also done when the user clicks on a button that has its CausesValidation property set to True.

To perform client-side validation, a browser must support Dynamic HTML, or DHTML. Because most browsers in use today support DHTML, validation can usually be done on the client. However, validation is always done on the server too when a page is submitted. ASP.NET does this validation after it initializes the page.

When ASP.NET performs the validation tests on the server, it sets the IsValid property of each validator to indicate if the test was successful. In addition, after all the validators are tested, it sets the IsValid property of the page to indicate if all the input data is valid. You can test this property in the event handler for the event that causes the page to be posted to the server. You’ll see how this works when you review the code-behind file for this form.

The validation controls on the Future Value form

Description

  1. You can use validation controls to test user input and produce error messages. The validation is performed when the focus leaves the control that’s being validated and also when the user clicks on a button control whose CausesValidation property is set to True.
  2. Each validation control is associated with a specific server control, but you can associate one or more validation controls with a single server control. 
     
  3. The validation controls work by running client-side script. Then, if the validation fails, the page isn’t posted back to the server. However, the validation is also performed on the server in case the client doesn’t support scripts. 
     
  4. If the client doesn’t support scripts, you can test whether validation has been successful on the server by testing whether the IsValid property of the page is True.

--------------------------------------------Figure 2-13   An introduction to the validation controls

How to use the required field validator

To use the required field validator, you set the properties shown in the table at the top of figure 2-14. These are the properties that are used by all the validators.

To start, you associate the validation control with a specific input control on the form through its ControlToValidate property. Then, when the focus leaves the input control or the user clicks on a button whose CausesValidation property is set to True, the validator checks whether a value has been entered into the input control. If not, the message in the ErrorMessage property is displayed.

When an error occurs, the Display property of the validation control determines how the message in the ErrorMessage property is displayed. When you use flow layout, Dynamic usually works the best for this property. If you use a validation summary control as explained in chapter 7, though, you can change this property to None.

If you look at the aspx code in this figure, you can see how the properties are set for the two required field validators that are shown in the previous figure. The first one validates the text box named txtInterestRate. The second one validates the text box named txtYears. This aspx code will be added after the end tag for the table in the code in figure 2-12.

How to use the range validator

The range validator lets you set the valid range for an input value. To use this control, you set the properties in the first table in figure 2-14, plus the properties in the second table. In particular, you set the minimum and maximum values for an input value.

For this control to work correctly, you must set the Type property to the type of data you’re testing for. Because the interest rate entry can have decimal positions, for example, the Type property for the first range validator is set to Double. In contrast, because the year entry should be a whole number, the Type property for the second range validator is set to Integer. You can see how all of the properties for the two range validators are set by reviewing the aspx code.

Common validation control properties  

 

 

 

 

Property

Description

ControlToValidate

The ID of the control to be validated.

Display

Determines how an error message is displayed. Specify Static to allocate space for the message in the page layout, Dynamic to have the space allocated when an error occurs, or None to display the errors in a validation summary control.

ErrorMessage

The message that’s displayed in the validation control when the validation fails.

 

 

 

 

Additional properties of a range validator  

 

 

 

 

Property

Description

MaximumValue

The maximum value that the control can contain.

MinimumValue

The minimum value that the control can contain.

Type

The data type to use for range checking (String, Integer, Double, Date, or Currency).

 

 

 

 

The aspx code for the validation controls on the Future Value form

  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
      ControlToValidate="txtInterestRate" Display="Dynamic"
      ErrorMessage="Interest rate is required.">
  </asp:RequiredFieldValidator&nbsp;>
  <asp:RangeValidator ID="RangeValidator1" runat="server" 
      ControlToValidate="txtInterestRate" Display="Dynamic"
      ErrorMessage="Interest rate must range from 1 to 20."
      MaximumValue="20" MinimumValue="1" Type="Double">
 
</asp:RangeValidator><br />
 
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
      ControlToValidate="txtYears" Display="Dynamic"
      ErrorMessage="Number of years is required.">
  </asp:RequiredFieldValidator>&nbsp;
  <asp:RangeValidator ID="RangeValidator2" runat="server"
      ControlToValidate="txtYears" Display="Dynamic"
      ErrorMessage="Years must range from 1 to 45."
      MaximumValue="45" MinimumValue="1" Type="Integer">
 
</asp:RangeValidator>

Description

  1. The required field validator is typically used with text box controls, but can also be used with list controls.
  2. The range validator tests whether a user entry falls within a valid range. 
     
  3. If the user doesn’t enter a value into the input control that a range validator is associated with, the range validation test passes. Because of that, you should also provide a required field validator if a value is required.

--------------------------------------------Figure 2-14   How to use the required field and range validators

How to add code to a form

To add the functionality required by a web form, you add Visual Basic code to its code-behind file. This code responds to the events that the user initiates on the form. This code also responds to events that occur as a form is processed.

How to use the Code Editor

To create and edit Visual Basic code, you use the Code Editor shown in figure 2-15. The easiest way to display the Code Editor window is to double-click the form or a control in the Web Forms Designer window. That displays the code-behind file for the form.

If you double-click the form in Design view, Sub and End Sub statements for the Load event of the page are generated. If you double-click a control, Sub and End Sub statements for the default event of the control are generated. If you double-click on a button control, for example, an event procedure (or event handler) for the Click event of that control is created. Then, you can enter the code for that procedure between the generated Sub and End Sub statements.

To create procedures for other events, you can use the drop-down lists at the top of the Code Editor window. The list at the left side of the window includes all of the available objects. When you select one of these objects, the list at the right side of the window lists all the events for that object. When you select an event, Visual Studio generates Sub and End Sub statements for the event handler.

You can also code general procedures by entering code directly into the Code Editor window. To create a Sub procedure, for example, you enter a Sub statement. And to create a Function procedure, or just function, you enter a Function statement. When you press the Enter key after entering one of these statements, the End Sub or End Function statement is generated for you. Then, you can enter the code required to implement the procedure between these statements, and you can call the procedure from another procedure.

As you work with the Code Editor, you’ll notice that it provides some powerful features that can help you code more quickly and accurately. One of the most useful of these features is the Auto List Members feature provided by IntelliSense. This feature displays a list of members that are available for an object when you type the object name and a period. Then, you can highlight the member you want by clicking on it, typing the first few letters of its name, or using the arrow keys to scroll through the list. In this figure, you can see the members that are listed for a drop-down list after the first character of the member name is entered. When you press the Tab key, the member you select is inserted into your code.

You can also use the Text Editor toolbar to work with code in the Code Editor. You can use it to perform functions such as commenting or uncommenting several lines of code at once, increasing or decreasing the indentation of several lines of code, and working with bookmarks. If you experiment with this toolbar, you should quickly see how it works.

A project with the Code Editor window displayed

Three ways to open or switch to a file in the Code Editor window

  • Select a web form in the Solution Explorer and click the View Code button at the top of the Solution Explorer. Double-click on a Visual Basic file (.aspx.vb or .vb) in the Solution Explorer. Or, click on a tab at the top of the Web Forms Designer (if the file is already open).

Four ways to start an event procedure

  1. Double-click on a blank portion of a web form to start an event procedure for the Load event of the page.
  2. Double-click on a control in the Web Forms Designer to start an event procedure for the default event of that control. 
     
  3. Select a control in the Web Forms Designer, click the Events button in the Properties window (the button with the lightening bolt), and double-click the event you want to create an event procedure for. 
     
  4. Select a control from the drop-down list at the top left of the Code Editor window, and select an event from the drop-down list at the top right. To create an event procedure for a page event, select (Page Events) from the first drop-down list.

Description

  1. The Code Editor includes powerful text editing features such as automatic indentation, syntax checking, and statement completion (as shown above).
  2. To enter a Sub procedure or function, you type the procedure or function from scratch, but Visual Studio will insert the End Sub or End Function statement.

--------------------------------------------Figure 2-15   How to use the Code Editor

How to use page and control events

The first table in figure 2-16 presents some of the common events for working with web pages. The Init and Load events of a page occur whenever a page is requested from the server. The Init event occurs first, and it’s used by ASP.NET to restore the view state of the page and its controls. Because of that, you don’t usually create an event handler for this event. Instead, you add any initialization code to the event handler for the Load event. You’ll see how this works in the next figure.

In contrast, the PreRender event is raised after all the control events for the page have been processed. It’s the last event to occur before a page is rendered to HTML. In later chapters, you’ll see a couple of cases in which this event is useful.

The second table in this figure lists some of the common events for web server controls. When the user clicks a button, for example, the Click event of that control is raised. Then, the page is posted back to the server, the event handlers for the Init and Load events of the page are executed, if present, followed by the event handler for the Click event of the control that was clicked.

The TextChanged event occurs when the user changes the value in a text box. In most cases, you won’t code an event handler for the TextChanged event. However, you might code an event handler for the CheckedChanged event that occurs when the user clicks a radio button or checks a check box. You might also code an event handler for the SelectedIndexChanged event that occurs when the user selects an item from a list.

If you want the event handler for one of these events to be executed immediately when the event occurs, you can set the AutoPostBack property of the control to True. Then, the event handler will be executed after the Init and Load event handlers for the page. Note that if you don’t set the AutoPostBack property to True, the event is still raised, but the event handler isn’t executed until another user action causes the page to be posted to the server. Then, the event handlers for the Init and Load events of the page are executed, followed by the event handlers for the control events in the order they were raised.

In this figure, you can see the event handler for the Click event of the Clear button on the Future Value form. Note that the name for this event handler is btnClear_Click, which is the ID of the button followed by the name of the event. Remember, though, that the Handles clause actually determines what event or events the procedure responds to. In this procedure, the value in the drop-down list is reset to 50, and the text boxes and label are reset to empty strings.

Incidentally, using the Handles clause is the default method for wiring events to their event handlers. However, you can also wire an event to an event handler by naming the event handler on the event attribute of a control. Although you’ll learn how this works in chapter 6, there’s usually no reason to change from using the Handles clause.

Common ASP.NET page events  

 

 

 

 

Event

Procedure name

Occurs when…

Init

Page_Init

A page is requested from the server. This event is raised before the view state of the page controls has been restored.

Load

Page_Load

A page is requested from the server, after all controls have been initialized and view state has been restored. This is the event you typically use to perform initialization operations such as retrieving data and initializing form controls.

PreRender

Page_PreRender

All the control events for the page have been processed but before the HTML that will be sent back to the browser is generated.

 

 

 

 

Common ASP.NET control events

 

 

 

 

Event Occurs when…
Click The user clicks a button, link button, or image button control.
TextChanged The user changes the value in a text box.
CheckedChanged The user selects a radio button in a group of radio buttons or selects or unselects a check box.
SelectedIndexChanged The user selects an item from a list box, a drop-down list, a check box list, or a radio button list.

 

 

 

 

Code for the Click event of the btnClear button

  Protected Sub btnClear_Click(ByVal sender As Object, _
         
ByVal e As System.EventArgs) Handles btnClear.Click
      ddlMonthlyInvestment.Text = 50
      txtInterestRate.Text = ""
      txtYears.Text = ""
      lblFutureValue.Text = ""
  End Sub

Description

  1. All of the events associated with an ASP.NET web page and its server controls are executed on the server. Because of that, the page must be posted back to the server to process any event for which you’ve coded an event handler. 
     
  2. When a page is posted back to the server, the Init and Load events are always raised so any event handlers for those events are run first. Next, the event handlers for any control events that were raised are executed in the ordered they were raised. When these event handlers finish, the PreRender event is raised and any event handler for that event is run.

--------------------------------------------Figure 2-16   How to use page and control events

Please check back tomorrow for the conclusion to this article series.

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 11 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials