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) ThenErrorProvider1.SetError(Textbox1, “The field cannot be empty!”)ElseErrorProvider1.SetError(Textbox1,Nothing)End If
If String.IsNullOrEmpty(Textbox2.Text.Trim) ThenErrorProvider1.SetError(Textbox2, “The field cannot be empty!”)ElseErrorProvider1.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 ThenMessageBox.Show(ErrorProvider.GetErrorMessages())‘ Error routine hereEnd If
Step one: Create a new module
Imports System.Runtime.CompilerServicesImports System.Text
Namespace ErrorProviderExtensionModule ErrorExtension<Extension()> _Public Function Validate( ByVal Epd As ErrorProvider, _
ByVal Control As Control, _
Optional ByVal ErrorMessage As String = “Field cannot be empty!”) As BooleanIf String.IsNullOrEmpty(Control.Text.Trim) ThenEpd.SetError(Control, ErrorMessage)Return FalseExit FunctionEnd IfEpd.SetError(Control, Nothing)Return TrueEnd Function
<Extension()> _Public Function HasErrors(ByVal Epd As ErrorProvider) As BooleanDim err e Nullable(Of Integer) = (From e In Epd.ContainerControl.Controls _Let msg = Provider.GetError(e) _Where msg.Length > 0 _Select e).CountIf err.GetValueOrDefault(0) > 0 ThenReturn TrueElseReturn FalseEnd IfEnd Function
<Extension()> _Public Function GetErrorMessages(ByVal Epd As ErrorProvider) As StringDim sb As New StringBuilderIf Epd.ContainerControl Is Nothing ThenReturn NothingExit FunctionEnd If
Dim err = From e In Epd.ContainerControl.Controls _Let message = Epd.GetError(e) _Where message.Length > 0 _Select message
If Not IsNothing(err) ThenDim i As Integer = 1For Each emsg As String In errsb.AppendLine(String.Format(“{0}: {1}”, i, emsg.ToString))i += 1Nextsb.AppendLine(“Please clear all the errors before continue!”)Return sb.ToStringExit FunctionEnd IfReturn NothingEnd Function
End ModuleEnd 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.ClickErrorProvider1.Validate(TextBox1, “TextBox1 cannot be blank!”)ErrorProvider1.Validate(TextBox2, “TextBox2 cannot be blank!”)
If ErrorProvider1.HasError ThenMessageBox.Show(ErrorProvider1.GetErrorMessages)Exit SubEnd If
‘Continue here if not errorEnd Sub
Note: Please refer to MSDN for supported version and methods.