Awarious OfficePortal - HRMS Application

How to show errors in VB.NET winforms using error provide when leaving textbox?

0 votes
asked Jun 22, 2013 in VB.NET by anonymous
recategorized Jun 24, 2013 by administrator

I know we can use error providers to show error messages. But what is the best way to do that in winforms whenever the focus is taken out of the text box? Please post me some sample code if possible. Thanks in advance.


1 Answer

+1 vote
answered Jun 24, 2013 by Aadhira (1,215 points)
selected Jun 30, 2013 by administrator
Best answer

As you said Error providers can show error messages for the controls which are having seterror. Error provider will accept the field to which the error message should be displayed also, the error message which needs to be displayed. That’s it.

CustomerDetailErrorProvider.SetError(txtFirstName, “First name is required”);

Following example has two textboxes, button and an error provider control. txtFirstName, txtLastName, btnSubmit and CustomerDetailErrorProvider. This example will show error messages whenever the textboxes lost focus, or whenever the Submit button clicked.

enter image description here

If we need to display error message whenever the textbox lost focus, then you may want to use “Validating” event that comes with the controls. This event will be raised whenever the text box lost focus.

You can have validating event for each text box. But that is really going to be looking ugly when we have 15 or 20 textboxes or controls to be validated on a single form. So, I have used a single validation method to validate. i.e I have attached single validation method for multiple controls. So, whenever any control attached to that event lost focus, then the validation method will be called.

In my example, AttachHandlers method will attach event handler (ControlsValidating) for both FirstName and LastName textboxes. ControlsValidating will get the control which raised the ‘Validating’ event, as a sender parameter. Then, that control will be validated by the “ValidateSingleControl” method. If the control is not valid, then it will add error message to the dictionary. If the control is valid, then it will remove the error message from the dictionary when there is any error.

One other thing to be noted is, each control has one common property call “Tag”. This can be used to set some value which can be used programmatically. In my example, I have used to hold some unique value for each control. (txtFirstName has “FirstName”, txtLastName has “LastName”) This tag will be used to identify each control, also the same tag value will be used to set error message in to the dictionary. So, that it can be set during ShowError method call.

ShowErrors() method will be going through each error messages in the dictionary, then find the control which matches the value that has in the control’s tag property, then SetError to that control. Hope fully this below example will help you.

Public Class frmCustomerDetail

    ReadOnly _errorMessages As Dictionary(Of String, String) = Nothing
    ReadOnly _controlsToBeValidated As List(Of Control) = Nothing

    Public Sub New()

        ''Dictionary to hold error message for any control. Key is controls Tag property, Value is error message
        ''Each controls tag property should be having some unique value
        _errorMessages = New Dictionary(Of String, String)

        ''To hold all controls to be validated when submit button clicked
        _controlsToBeValidated = New List(Of Control)

        ''To fill all controls to be validated when submit button clicked

        ''To attach event handlers
    End Sub

    Private Sub AttachHandlers()

        ''Attaching both textboxes to the 'Validating' event with method 'Controls__Validating'
        AddHandler txtFirstName.Validating, AddressOf Controls__Validating
        AddHandler txtLastName.Validating, AddressOf Controls__Validating
    End Sub

    ''This event will be called for FirstName and LastName Textbox when the controls lost focus
    Private Sub Controls__Validating(sender As Object, e As EventArgs)
        Dim _currentControl As Control = DirectCast(sender, Control)
    End Sub

    Private Sub ValidateAllControls(ByVal _controlsToValidate As List(Of Control))
        For Each _controlToValidate As Control In _controlsToValidate

    End Sub

    Private Sub ValidateSingleControl(_controlToValidate As Control)
        Dim _textBox As TextBox = IIf(_controlToValidate.GetType().IsAssignableFrom(GetType(TextBox)), DirectCast(_controlToValidate, TextBox), Nothing)

        If Not _textBox Is Nothing AndAlso Not String.IsNullOrEmpty(_textBox.Text) Then
            If Not _errorMessages.ContainsKey(_controlToValidate.Tag) Then
                _errorMessages.Add(_controlToValidate.Tag, _controlToValidate.Tag & " is required.")
            End If
        End If
    End Sub

    ''This will go through the error messages dictionary and SetError for any control which are have error message
    Public Sub ShowErrors(_errorMessages As IDictionary(Of String, String))

        If Not _errorMessages Is Nothing Then
            For Each _property As String In _errorMessages.Keys
                Dim _formControls As List(Of Control) = Me.Controls.Cast(Of Control).ToList()
                Dim _formControl As Control = _formControls.FirstOrDefault(Function(_control) _control.Tag = _property)
                If Not _formControl Is Nothing Then
                    CustomerDetailErrorProvider.SetError(_formControl, _errorMessages(_property))
                End If
        End If
    End Sub

    Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
    End Sub

    Private Sub FillControlsToValidate()
    End Sub

End Class

Your answer


Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2019