Wednesday, September 1, 2010

VB.NET - How To Extend A Custom Method to Error Provider For Field Validation


The concept is very simple, instead of coding the Error Provider Control to validate field one by one; we add custom functionality to Error Provider that can be call without creating a new derived type.

For example
From:
If String.IsNullOrEmpty(Textbox1.Text.Trim) Then
            ErrorProvider1.SetError(Textbox1, “The field cannot be empty!”)
Else
            ErrorProvider1.SetError(Textbox1,Nothing)
End If

If String.IsNullOrEmpty(Textbox2.Text.Trim) Then
            ErrorProvider1.SetError(Textbox2, “The field cannot be empty!”)
Else
            ErrorProvider1.SetError(Textbox2,Nothing)
End If

To:
ErrorProvider1.Validate(TextBox1, “This field cannot be empty!”)
ErrorProvider1.Validate(TextBox2, “This field cannot be blank!”)
If ErrorPrivider1.HasError Then
            MessageBox.Show(ErrorProvider.GetErrorMessages())
‘ Error routine here
End If


Step one: Create a new module
Imports System.Runtime.CompilerServices
Imports System.Text

Namespace ErrorProviderExtension
            Module ErrorExtension
                       
            <Extension()> _
            Public Function Validate( ByVal Epd As ErrorProvider, _
                  ByVal Control As Control, _
                  Optional ByVal ErrorMessage As String = “Field cannot be empty!”As Boolean
                          If String.IsNullOrEmpty(Control.Text.Trim) Then
                                      Epd.SetError(Control, ErrorMessage)
                                      Return False
                                      Exit Function
                          End If
                                   
                          Epd.SetError(Control, Nothing)
                          Return True
             End Function

            <Extension()> _
            Public Function HasErrors(ByVal Epd As ErrorProvider) As Boolean
                        Dim err e Nullable(Of Integer) = (From e In Epd.ContainerControl.Controls _
                                                                                 Let msg = Provider.GetError(e) _
                                                                                 Where msg.Length > 0 _
                                                                                 Select e).Count
                        If err.GetValueOrDefault(0) > 0 Then
                                    Return True
                        Else
                                    Return False
                        End If
            End Function

            <Extension()> _
            Public Function GetErrorMessages(ByVal Epd As ErrorProvider) As String
                        Dim sb As New StringBuilder
                                  
                        If Epd.ContainerControl Is Nothing Then
                                    Return Nothing
                                    Exit Function
                        End If

                        Dim err = From e In Epd.ContainerControl.Controls _
                                          Let message = Epd.GetError(e) _
                                          Where message.Length > 0 _
                                          Select message

                        If Not IsNothing(err) Then
                                  Dim i As Integer = 1
                                  For Each emsg As String In err
                                            sb.AppendLine(String.Format(“{0}: {1}”, i, emsg.ToString))
                                             i += 1
                                  Next
                                  sb.AppendLine(“Please clear all the errors before continue!”)
                                  Return sb.ToString
                                  Exit Function
                       End If
                                   
                       Return Nothing
            End Function

            End Module
End Namespace

Next, create a new Windows®Form; drag an ErrorProvider, two TextBox and one Button onto it, then
Imports rootnamespace.ErrorProviderExtension

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
             ErrorProvider1.Validate(TextBox1, “TextBox1 cannot be blank!”)
             ErrorProvider1.Validate(TextBox2, “TextBox2 cannot be blank!”)

             If ErrorProvider1.HasError Then
                 MessageBox.Show(ErrorProvider1.GetErrorMessages)
                 Exit Sub
             End If

            ‘Continue here if not error
            End Sub

Note: Please refer to MSDN for supported version and methods.