Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Windows Forms Validation w/ ErrorProvider Control Quickly (Validate Whole Form at Once)

0.00/5 (No votes)
26 Apr 2008 2  
Windows Forms Validation w/ ErrorProvider Control Quickly (Validate Whole Form at Once)

Introduction

Are you frustrated with the error-provider. All you want is just one method that allows you to validate your entire form at once before you submit. Here it is...

Background

I have a general method that is probably similar to everyone elses. I have a grid, and then you open up a form to add/edit an object. You need to validate that the information was entered and it was entered correctly.

The problem with me.validate() is that is only validates the last focused control. ValidateChildren seemed like a viable solution, but it didn't validate everything for me either.

So I was left with what .Net provided, and made a simple class to take advantage of how it wanted to work. If it wanted to validate after each control lost focus, then I would just loop through all the controls and give it focus, and call validate. This worked great until I started including tabcontrols on forms, and then I found out that it would only validate properly for the tab page that was currently selected. I had to go back and add a special condition for this case. I use devexpresses control set, so my special case is that tab control, but with another couple lines of code, you can make it handle any special case such as the windows tab control, possibly split containers, etc.

Using the code

Put an ErrorProvider on each form. I like to name mine ErrorProvider on every form so I don't have to change stuff in each code. Turn autovalidate to "enable allow focus change" for the best user experience.

Put an e.cancel = false in the FormClosing event so that the cancel button, and the x button at the top of the form works even when the form isn't validated.

Make sure your save button has causesvalidation = true along with any control you want to validate. This is the default I believe. Make sure other buttons, especially the cancel button has causesvalidation=false so that they won't validate.

Then once you're in the habit of doing that on each form, you can use the template below and some copy and pasting to put validators in for each control you want to validate, and then when you hit your save button... You just have to call "If Validation.FormIsValid Then..." and your entire form is validated in one statement.

It is just that easy... I like Asp.Nets method better, but with this class, you can live with it and maybe even love it.....

// Here is some code on the form that will help you out...
Private Sub frmCompany_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

    Try

      e.Cancel = False

    Catch ex As Exception

      Errors.HandleError(ex)

    End Try

  End Sub

Private Sub txtName_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtName.Validating

    Try

      If Not txtName.Text.Length > 0 Then
        ErrorProvider.SetError(txtName, "You must include a name.")
        e.Cancel = True
      Else
        ErrorProvider.SetError(txtName, String.Empty)
      End If

    Catch ex As Exception

      Errors.HandleError(ex)

    End Try

  End Sub 
 
End Class  
 // Here is the code for the class
Imports DevExpress.XtraTab
Imports System.Collections.Generic
Imports System.Windows.Forms
Imports System.Windows.Forms.Form

Public Class Validation

#Region "Public Shared Methods"

  Public Shared Function FormIsValid(ByRef objForm As Form) As Boolean

    Dim Valid As Boolean = True
    Validate(objForm, objForm.Controls, Valid)

    objForm.Focus()
    If Not objForm.Validate Then Valid = False

    Return Valid
    
  End Function

  Public Shared Function FormIsValid(ByRef objform As Form, ByRef TopLevelControl As Control) As Boolean

    Dim Valid As Boolean = True
    Validate(objform, TopLevelControl.Controls, Valid)

    objform.Focus()
    If Not objform.Validate Then Valid = False

    Return Valid
   
  End Function

  Private Shared Sub Validate(ByRef objForm As Form, ByRef objControls As System.Windows.Forms.Control.ControlCollection, ByRef Valid As Boolean)

    For Each objControl As Control In objControls

      If Not TypeOf objControl Is RadioButton Then

        objControl.Focus()
        If Not objForm.Validate() Then Valid = False

        If TypeOf objControl Is XtraTabControl Then

          Dim TabControl As XtraTabControl = objControl
          Dim Index As Integer = TabControl.SelectedTabPageIndex

          For Each objTab As XtraTabPage In TabControl.TabPages
            TabControl.SelectedTabPage = objTab
            Validate(objForm, objTab.Controls, Valid)
          Next

          TabControl.SelectedTabPageIndex = Index

        ElseIf objControl.HasChildren Then

          Validate(objForm, objControl.Controls, Valid)

        End If

      End If

    Next

  End Sub

#End Region

End Class 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here