Friday, July 3, 2009

Validation of Multiple Controls in Single Function

Suppose we may want to validate the various Windows Forms Controls(text box, combobox, list box etc) using one validation function.

The Validating Event of Windows Forms Controls helps in this.

The Validating event will be thrown when we press tab to move to next control.

The following validation function is used to validate different controls.

1. Drag label onto form and name it as lblName and change the text to Name.
2. Drag text box onto form and name it as txtName.
3. Drag lable onto form and name it as lblAge and change the text to Age.
4. Drag text box onto form and name it as txtAge.
5. Drag lable onto form and name it as lblGender and change the text to Gender.
6. Drag combo box onto form and name it as cmbAge.
7. Drag ErrorProvider Control onto the form


Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Populate the combo box
cmbGender.Items.Add("Male")
cmbGender.Items.Add("Female")

txtName.Focus()
End Sub

'Validating Event
Private Sub cmbGender_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cmbGender.Validating
If Not validatingControls(sender) Then
Return
End If

End Sub

Private Sub txtName_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtName.Validating
If Not validatingControls(sender) Then
Return
End If
End Sub

Private Sub txtAge_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtAge.Validating
If Not validatingControls(sender) Then
Return
End If
End Sub

Private Function validatingControls(ByVal Ctrl As Control) As Boolean
Dim myComboBox As ComboBox

If TypeOf Ctrl Is TextBox Then
If Ctrl.Text = "" Then
ErrorProvider1.SetError(Ctrl, "Enter text")
Ctrl.Focus()
Return False
End If

ElseIf TypeOf Ctrl Is ComboBox Then
myComboBox = CType(Ctrl, ComboBox)
If myComboBox.SelectedIndex < 0 Then
ErrorProvider1.SetError(Ctrl, "Select value")
Ctrl.Focus()
End If
End If

Return True

End Function



In this example I am validating the control using Validating Event but you can call this by passing the Control individually (Example on Submit Button).

No comments:

Post a Comment