Click here to Skip to main content
15,885,435 members
Articles / Programming Languages / Visual Basic
Article

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

Rate me:
Please Sign up or sign in to vote.
3.67/5 (2 votes)
26 Apr 2008CPOL2 min read 51.6K   34   3
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.....

VB.NET
// 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
VB.NET
End Class 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralSorry, copied wrong code Pin
tricos27-Apr-08 17:20
tricos27-Apr-08 17:20 
GeneralNot ready for approval [modified] Pin
Member 9626-Apr-08 19:56
Member 9626-Apr-08 19:56 
GeneralNo Pin
Maruf Maniruzzaman26-Apr-08 19:54
Maruf Maniruzzaman26-Apr-08 19:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.