ValidationDemo.vb

 1: ' Validation Demo - Shows some ways to validate input.
 2: ' Written 2/2010 by Wayne Pollock, Tampa Florida USA
 3: 
 4: Public Class ValidationDemo
 5:     Private Sub ExitBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitBtn.Click
 6:         Me.Close()
 7:     End Sub
 8: 
 9:     ' This event handler gets called when the user tries to enter the
10:     ' data by clicking on the button (or hitting Return):
11: 
12:     Private Sub EnterBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnterBtn.Click
13:         Dim value As Integer
14: 
15:         ' Don't try to Parse if the box is empty (or an Exception is thrown):
16:         If DataTxtBox.Text <> "" Then
17:             value = Integer.Parse(DataTxtBox.Text)
18:         End If
19: 
20:         ' Note the use of the "short-cut "OrElse" Boolean operator:
21:         If DataTxtBox.Text = "" OrElse value < 0 OrElse value > 999999 Then
22:             DataTxtBox.BackColor = Color.PaleVioletRed
23:             ErrorMsgLbl.Visible = True
24:             MessageBox.Show("You must enter a whole number between" _
25:                             & Environment.NewLine _
26:                             & "0 and 1,000,000")
27:             ResultTxtBox.Clear()
28:         Else  ' Data is Validated, so let's do something with it:
29:             ResultTxtBox.Text = value.ToString("N0")
30:             DataTxtBox.Focus()
31:             DataTxtBox.SelectAll() ' Highlight the old text for easy changing
32:         End If
33:     End Sub
34: 
35:     ' This Event handler gets called on every keystoke when the
36:     ' Data textbox has the focus:
37:     Private Sub DataTxtBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataTxtBox.TextChanged
38:         Dim num As Integer
39: 
40:         ' Note the TryParse will fail if the input has commas or other
41:         ' illegal characters.  It will also fail if the value over- or
42:         ' under-flows:
43:         If Integer.TryParse(DataTxtBox.Text, num) Then
44:             DataTxtBox.BackColor = Color.White
45:             ErrorMsgLbl.Visible = False
46:             EnterBtn.Enabled = True
47: 
48:             ' Special case: An empty box shouldn't show an error message,
49:             ' but the Enter button should still be disabled:
50:         ElseIf DataTxtBox.Text = "" Then
51:             DataTxtBox.BackColor = Color.White
52:             ErrorMsgLbl.Visible = False
53:             EnterBtn.Enabled = False
54: 
55:             ' Otherwise, indicate an error:
56:         Else
57:             DataTxtBox.BackColor = Color.PaleVioletRed
58:             ErrorMsgLbl.Visible = True
59:             EnterBtn.Enabled = False
60:         End If
61:     End Sub
62: End Class