Home > Articles

Handling Exceptions

This chapter is from the book

Validating User Input

To make your application as robust as possible, the best solution to invalid or incorrect user input is to prevent the entry of "bad" data as often as possible. Validating user input before hand provides a better solution than very complex error-handling code that might add a great deal of resource overhead to your program. Four basic techniques are used to validate user input:

  • Restricting the available values by using the proper type of control, configured with a specific list of allowed values. Controls such as RadioButton, ListBox, ComboBox, and CheckBox are often used for this type of validation. Configuring properties of the controls allows additional restriction of user input, such as controlling the case or length of TextBox input.

  • Restricting data entry through controls by enabling or disabling them based on the state of other controls. As an example of this technique, a set of controls allowing the entry of address information might remain disabled until a valid CustomerID has been selected in another control.

  • Capturing and evaluating user keystrokes and allowing only acceptable values to be recognized. This might be used to prevent the entry of symbol or alphabetic characters within a control that should hold only numeric characters.

  • Evaluating a control's data as a whole and warning the user of incorrect or unacceptable values. This is often used to warn a user when attempting to change focus from the control or save the form.

Control-Based Validation

Restriction of allowable values within a control was discussed at greater length in Chapter 2, "Controls on Forms." In addition to simply restricting input to a selection from a list of values, control properties can be configured to further limit possible input values. Of note are the CharacterCasing and MaxLength properties used in text input controls such as the TextBox.

CharacterCasing

The CharacterCasing property of a TextBox control can be used to change all input alphabetic characters to a particular case. The options for the CharacterCasing property are Normal (the default, which does not change the case of input characters), Upper (changes all the characters to uppercase), and Lower (changes all the characters to lowercase).

MaxLength

The MaxLength property of a TextBox or ComboBox is used to restrict the maximum number of characters the user can input into the control. A value of 0 (the default) specifies no specific limit for the number of characters that can be entered by the user. This property does not restrict the length of values that can be set programmatically.

Control-Access Restriction

Manipulating access properties such as the Enabled or ReadOnly properties can restrict data entry access within a control. When a control's Enabled value is set to false, it cannot receive focus. If the ReadOnly property of a TextBox control is set to true, it can still receive focus, allowing users to scroll through its contents while preventing changes.

Keystroke-Level Validation

When a user presses a key, three events are fired in order:

  1. KeyDown

  2. KeyPress

  3. KeyUp

The KeyPress event can be used to intercept input keyboard characters and perform validation tasks through the use of the KeyPressEventArgs class before the KeyUp event is handled. Table 3.4 details some important properties of the KeyPressEventArgs class.

Table 3.4 Important Properties of the KeyPressEventArgs Class

Property

Description

Handled

Whether the event has been handled.

KeyChar

The character value corresponding to the pressed key.


The KeyPress event fires only for keys that generate character values, excluding function, control, and cursor-movement keys. To respond to the excluded keys, you must use the KeyDown and KeyUp events instead. These use the properties of the KeyEventArgs class, detailed in Table 3.5.

Table 3.5 Important Properties of the KeyEventArgs Class

Property

Description

Alt

Is true if the Alt key is pressed; otherwise, is false.

Control

Is true if the Ctrl key is pressed; otherwise, is false.

Handled

Indicates whether the event has been handled.

KeyCode

The keyboard code for the event. Its value is one of the values specified in the Keys enumeration.

KeyData

The key code for the pressed key, along with modifier flags that indicate the combination of Ctrl, Shift, and Alt keys that were pressed at the same time.

KeyValue

An integer representation of the KeyData property.

Modifiers

Modifier flags that indicate which combination of modifier keys (Ctrl, Shift, and Alt) was pressed.

Shift

Is true if the Shift key was pressed; otherwise, is false.


NOTE

By default, only the control, which currently has the focus, responds to the KeyDown, KeyPress, and KeyUp events. However, if you set the KeyPreview property of a form to true, the form can also handle the same three events before the control with the current focus handles them, allowing two tiers of keystroke-level validation—at the form level and at the control level.

Field-Level Validation

Validation also can be performed to include the entire value entered within a control by configuring validation code to run before focus is lost or the form is closed. When a user enters or leaves a field, the following events occur in order:

  1. Enter—Occurs when a control is entered

  2. GotFocus—Occurs when a control receives focus

  3. Leave—Occurs when focus leaves a control

  4. Validating—Occurs when a control is validating

  5. Validated—Occurs when a control is finished validating

  6. LostFocus—Occurs when a control loses focus

The Validating event is the ideal place to store the validating logic for a field; we discuss the Validating event in the next section.

The Validating Event

The Validating event is ideal for input value validation. You can write code to check the values presented and display an error message to the user or prevent the loss of focus from the current control until the value has been corrected.

The Focus method of the control can be used to redirect focus to the same control programmatically. Alternatively, the Cancel property of the CancelEventArgs object can be set to true, to prevent the transfer of focus from the current control.

TIP

Closing a form fires a Validating event. Therefore, if you want to use the Cancel property of the CancelEventArgs to prevent loss of focus, this will also prevent the user from closing the form. To avoid this, you need to code the event handling to reset the Cancel value only when the mouse is inside the form's client area. This allows the mouse to close the form using the Close button in the title bar.

The Validated event occurs after validation has occurred. It can be used to perform actions based on the validated values, such as enabling or disabling other controls, as discussed previously in this section.

The CausesValidation Property

When using the Validating event to retain the focus in a control until you receive a valid input value, you can prevent the user from being able to obtain help on what constituted a valid input value by clicking another control such as the Help button in the toolbar. This is a result of the default setting (true) of the CausesValidation property of the Button control.

If you set the CausesValidation property of the Help button control to false, the control can act without triggering the Validating event in the control with current focus.

The ErrorProvider Component

The ErrorProvider component provided within the Visual Studio .NET toolbox allows the display of error validation messages. A small icon includes a message that appears as a ToolTip when the user hovers the cursor over the displayed icon. Table 3.6 details the most important members of the ErrorProvider class.

Table 3.6 Important Members of the ErrorProvider Class

Member

Type

Description

BlinkRate

Property

Specifies the rate at which the error icon flashes.

BlinkStyle

Property

Specifies a value indicating when the error icon flashes.

ContainerControl

Property

Specifies the parent control of the ErrorProvider control.

GetError

Method

Returns the error description string for the specified control.

Icon

Property

Specifies an icon to display next to the parent control. The icon is displayed only when an error-description string (SetError) has been set for the parent control.

SetError

Method

Sets the error-description string for the specified control.

SetIconAlignment

Method

Specifies the location at which to place an error icon in relation to the control.

SetIconPadding

Method

Specifies the amount of extra space to leave between the specified control and its error icon.


This component offers many advantages over opening separate message boxes for each possible error, which can confuse users and complicate the desktop. The ErrorProvider component provides a simple user-friendly display that rapidly draws a user's attention to the control failing input validation. Figure 3.2 shows a form that includes an ErrorProvider component.

Figure 3.2Figure 3.2   A form displaying an example of the ErrorProvider component.

The following code shows how the ErrorProvider component can be used together with the Validating event to display errors during validation:

private void txtGallons_Validating(object sender, 
  System.ComponentModel.CancelEventArgs e)
{
  try
  {
    decimal decGallons = Convert.ToDecimal(txtGallons.Text);
    if (decGallons > 0) 
      errorProvider1.SetError(txtGallons, "");
    else
      errorProvider1.SetError(
        txtGallons, "Please enter value > 0");
  }
  catch(Exception ex)
  {
    errorProvider1.SetError(txtGallons, ex.Message);
  }
}

In this section, we discussed various techniques that can be used for user input validation. You also learned how the ErrorProvider component can be used to point to errors when the user enters input data on a Windows Form.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020