Inheritance and Windows Forms - Validating Inputs
(Page 3 of 5 )
So far we managed to have 2 forms, with the same basic controls and functionality, much like the “Employee” class and the other inherited classes “Manager” and “Technician”. It shouldn’t stop here, should it?
Uhm, no.
As a matter of fact, if I am adding a Manager, or a Technician, then I want to validate the inputs. We will not, however, make the validation on each form alone (remember the “ManageEmployee” Form). We will put the validation code and make use of the error provider on the “ManageEmployee” form.
We will add a function “IsValidInputs” which will validate the user inputs in the text boxes. It will also set the set the properties of the error provider if any errors were found.
Protected
Function IsValidInputs() As Boolean
Dim strEmployeeName As String
Dim strEmployeeAge As String
'Age should be integer, but not we will be reading from the'
'text box, and we need to validate that it is an integer'
Dim bIsValidInputs As Boolean = True
'we start with the assumption that the inputs are valid'
Try
strEmployeeName = txtName.Text.Trim
strEmployeeAge = txtAge.Text.Trim
'check if the Name is empty'
If strEmployeeName = String.Empty Then
bIsValidInputs = False
errProvider.SetError(txtName, "Please add a Name.")
Else
'Make sure to clear the Error Provider
errProvider.SetError(txtName, "")
End If
If strEmployeeAge = String.Empty Then
bIsValidInputs = False
errProvider.SetError(txtAge, "Please add an Age.")
Else
'Make sure to clear the Error Provider'
errProvider.SetError(txtAge, "")
End If
If Not IsNumeric(strEmployeeAge) Then
bIsValidInputs = False
errProvider.SetError(txtAge, "Age should be a number.")
Else
'Make sure to clear the Error Provider'
errProvider.SetError(txtAge, "")
End If
Return bIsValidInputs
Catch oException As Exception
'Handle any unexpected errors here'
End Try
End Function
Let’s get back to the object oriented. The function above should be only visible to the form and the forms inheriting from it. (Yes, it should be protected.)
Next: Carrying Out the Scenario >>
More Visual Basic.NET Articles
More By Mohammed Qattan