Validation and ErrorProvider

Jarod

Regular
Joined
Feb 5, 2003
Messages
82
Location
Bruxelles
Hello

I have a form with some TextBoxes I would like to validate.
Say for example:
- 1 form
- 2 Textboxes
- 1 Button
- 1 Error Provider

for each TextBox, code like
Visual Basic:
  Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
    If Me.TextBox1.Text = String.Empty Then
      Me.ErrorProvider1.SetError(Me.TextBox1, "Required")
    End If
  End Sub

when I tab from one TextBox to another, I can see the ErrorProvider in action if the TextBox was left blank.

But say the form loads, focus on first TextBox and directly click on button (no tab). In the click event I want to validate my page so do validate()
But my second TextBox is not validated (because it didn't got focus at any moment)

How can I ask that ALL my controls should be validated and not only the last one ?

Thanks,
 
Is there a normal way or do I have to do something like :
Visual Basic:
    Dim myControl As Control
    For Each myControl In Me.Controls
      myControl.Focus()
    Next
to trick and simulate the "user tabs" ?
 
Well, I don't know if that would work or not. You will probably have
to do a little bit of manual checking in the OK button yourself. So,
in the Closing event you might do this:
Visual Basic:
Dim errorMsg As String

If TextBox2.Text.Length < 9 Then errorMsg &= " - Field 2 must be at least 9 characters" & ControlChars.CrLf
If Not IsNumeric(TextBox3) Then errorMsg &= " - Field 3 must be a numeric value" & ControlChars.CrLf
If TextBox4.Text = "" Then errorMsg &= " - Field 4 is a required field" & ControlChars.CrLf
If Not IsDate(TextBox5)  Then errorMsg &= " - Field 5 must be a valid date" & ControlChars.CrLf

If errorMsg.Length > 0 Then
  MessageBox.Show("There were errors in the form you filled out:" & _
    ControlChars.CrLf & ControlChars.CrLf & errorMsg)
  e.Cancel = True
End If
 
Back
Top