What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleMake an ExtenderProvider to validate required fields in VB .NET
DescriptionThis example shows how to make an ExtenderProvider to validate required fields in VB .NET. The provider catches its clients' Validating events and verifies that the values aren't blank.
KeywordsExtenderProvider, required, validation, validate
CategoriesSoftware Engineering, Controls, VB.NET
See Tutorial: Introduction to ExtenderProviders in VB .NET for an overview of creating ExtenderProviders.

This provider stores error messages in a hashtable named m_MissingMessages. It also adds an event handler to catch each client control's Validating event.

When that event fires, the provider's ValidateTextBox subroutine determines whether the client TextBox is blank. If the TextBox is blank, it assigns an error to the TextBox using the provider's embedded ErrorProvider component.

To help the program decide whether it is safe to exit, the provider includes a HasError function. This function validates all of the registered client controls to display errors for any that are blank. It then moves focus to the one with the smallest TabIndex value and displays that control's error message in a message box.

Imports System.ComponentModel

<ToolboxBitmap(GetType(IsRequiredProvider), _
    "required_provider.bmp"), _
 ProvideProperty("IsRequiredMessage", GetType(Control))> _
Public Class IsRequiredProvider
    Inherits System.ComponentModel.Component
    Implements IExtenderProvider

... Component Designer generated code ...

    ' The error message to display if a control is missing.
    Private m_MissingMessages As New Hashtable

    Private m_Enabled As Boolean = True
    <Category("Behavior"), _
     DefaultValue(True)> _
    Public Property Enabled() As Boolean
            Return m_Enabled
        End Get
        Set(ByVal Value As Boolean)
            m_Enabled = Value
        End Set
    End Property

    ' We can extend TextBoxes.
    Public Function CanExtend(ByVal client_control As _
        Object) As Boolean Implements _
        Return (TypeOf client_control Is TextBox)
    End Function

    ' Return this control's is required message.
    <Category("Validation"), _
     DefaultValue("")> _
    Public Function GetIsRequiredMessage(ByVal _
        client_control As Control) As String
        ' See if we have a message for this control.
        If m_MissingMessages.Contains(client_control) Then
            ' Return the message.
            Return DirectCast(m_MissingMessages(client_control), _
            ' We have no message for this control.
            Return Nothing
        End If
    End Function

    ' Set the control's missing message.
    <Category("Validation"), _
     DefaultValue("")> _
    Public Sub SetIsRequiredMessage(ByVal client_control As _
        Control, ByVal missing_message As String)
        ' If this control is now required, remove it.
        If m_MissingMessages.Contains(client_control) Then
            RemoveHandler client_control.Validating, _
                AddressOf Client_Validating
        End If

        ' If the new message is non-blank, add it.
        If Not (missing_message Is Nothing) Then
            If missing_message.Length > 0 Then
                m_MissingMessages.Add(client_control, _
                AddHandler client_control.Validating, _
                    AddressOf Client_Validating
            End If
        End If
    End Sub

    ' A client is validating. See if it is blank.
    Private Sub Client_Validating(ByVal sender As Object, _
        ByVal e As System.ComponentModel.CancelEventArgs)
        If Not m_Enabled Then Exit Sub
        ValidateTextBox(DirectCast(sender, TextBox))
    End Sub

    ' Validate this control.
    Private Sub ValidateTextBox(ByVal client_control As _
        If client_control.Text.Trim.Length > 0 Then
            ' It's not blank.
            Me.errOutOfRange.SetError(client_control, "")
            ' It's blank.
            Dim missing_message As String
            Me.errOutOfRange.SetError(client_control, _
                DirectCast(m_MissingMessages(client_control), _
        End If
    End Sub

    ' If some control has an error, display its error
    ' message,
    ' set focus to it, and return True. If all controls are
    ' okay, then return False.
    Public Function HasError() As Boolean
        If Not m_Enabled Then Return False

        ' Make sure all controls have been validated.
        For Each text_box As TextBox In _
        Next text_box

        ' Find the first control in the tab order with an
        ' error.
        Dim first_text_box As TextBox = Nothing
        Dim first_tab_index As Integer = Integer.MaxValue
        For Each text_box As TextBox In _
            ' See if the control has an error.
            If errOutOfRange.GetError(text_box).Length > 0 _
                If text_box.TabIndex < first_tab_index Then
                    first_text_box = text_box
                    first_tab_index = text_box.TabIndex
                End If
            End If
        Next text_box

        ' See if any control has an error.
        If Not (first_text_box Is Nothing) Then
            Return True
        End If

        Return False
    End Function
End Class
At design time, you set the IsRequiredMessage for TextBoxes that you want to be required. The main program doesn't need to use any code to validate TextBoxes.

If you want to ensure that all TextBoxes are filled in, call the HasError function in the form's Closing event handler to see if it is safe to close the form.

Private Sub Form1_Closing(ByVal sender As Object, ByVal e _
    As System.ComponentModel.CancelEventArgs) Handles _
    e.Cancel = IsRequiredProvider1.HasError()
End Sub

Private Sub btnOk_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnOk.Click
End Sub

Private Sub btnCancel_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnCancel.Click
    IsRequiredProvider1.Enabled = False
End Sub
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.