Exercise: Write code to validate text boxes

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

The answer to the exercise will be included and explained if you attend the Wise Owl course listed below!

Category ==> Visual Basic 2010  (42 exercises)
Topic ==> Form validation  (3 exercises)
Level ==> Relatively easy
Course ==> WinForms using VB
Before you can do this exercise, you'll need to download and unzip this file (if you have any problems doing this, click here for help).

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Add the existing form in the folder shown above into your project.  When you run your application, you should see this:

Visual Basic 2010 exercise - Form validation (image 1)

You should call the ValidateChildren method from the APPLY button

Attach code to the Validating event of the txtName textbox, so that a message appears if you leave the name blank:

Visual Basic 2010 exercise - Form validation (image 2)

Display a message if a user leaves the name blank

Repeat this trick for the txtAge field, this time checking also that the age entered is a whole number (one way to do this is with :Try ... Catch ... End Try, within which you can attempt to convert the txtAge field's text property to an integer.

Visual Basic 2010 exercise - Form validation (image 3)

What you should see if you enter an invalid age (or none at all)

Finally, add code to the Age field's Validated event so that the age is increased by 10 years after it has been checked:

Visual Basic 2010 exercise - Form validation (image 4)

Reflecting the fact that everyone lies on dating agency application forms ...

You should now see that the Validated event fires whether you change the value in their Age text box or not.  How might you stop your age increasing by 10 years every time a user leaves the Age text box?

This page has 0 threads Add post