Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
22
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

Chapter 24

Performing Validation

After completing this chapter, you will be able to:

Examine the information entered by a user to ensure that it does not violate any application or business rules.

Use data binding validation rules to validate information entered by a user.

Perform validation effectively but unobtrusively.

In the previous two chapters, you have seen how to create a Microsoft Windows Presentation Foundation (WPF) application that uses a variety of controls for data entry. You created menus to make the application easier to use. You have learned how to trap events raised by menus, forms, and controls so that your application can actually do something besides just look pretty. Although careful design of a form and the appropriate use of controls can help to ensure that the information entered by a user makes sense, you often need to perform additional checks. In this chapter, you will learn how to validate the data entered by a user running an application to ensure that it matches any business rules specified by the application’s requirements.

Validating Data

The concept of input validation is simple enough, but it is not always easy to implement, especially if validation involves cross-checking data the user has entered into two or more controls. The underlying business rule might be relatively straightforward, but all too often, the validation is performed at an inappropriate time, making the form difficult (and infuriating) to use.

Strategies for Validating User Input

You can employ many strategies to validate the information entered by the users of your

applications. A common technique that many Microsoft Windows developers familiar with previous versions of the Microsoft .NET Framework use is to handle the LostFocus event of controls. The LostFocus event is raised when the user moves away from a control. You can

add code to this event to examine the data in the control that the user is vacating and ensure that it matches the requirements of the application before allowing the cursor to move away. The problem with this strategy is that often you need to cross-check data entered into

one control against the values in others, and the validation logic can become quite convoluted; you frequently end up repeating similar logic in the LostFocus event handler for sev-

473

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]