Export (0) Print
Expand All

ErrorProvider Class

Provides a user interface for indicating that a control on a form has an error associated with it.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

'Declaration
<ComplexBindingPropertiesAttribute("DataSource", "DataMember")> _
Public Class ErrorProvider _
	Inherits Component _
	Implements IExtenderProvider, ISupportInitialize

The ErrorProvider type exposes the following members.

  NameDescription
Public methodErrorProviderInitializes a new instance of the ErrorProvider class and initializes the default settings for BlinkRate, BlinkStyle, and the Icon.
Public methodErrorProvider(ContainerControl)Initializes a new instance of the ErrorProvider class attached to a container.
Public methodErrorProvider(IContainer)Initializes a new instance of the ErrorProvider class attached to an IContainer implementation.
Top

  NameDescription
Public propertyBlinkRateGets or sets the rate at which the error icon flashes.
Public propertyBlinkStyleGets or sets a value indicating when the error icon flashes.
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public propertyContainerGets the IContainer that contains the Component. (Inherited from Component.)
Public propertyContainerControlGets or sets a value indicating the parent control for this ErrorProvider.
Public propertyDataMemberGets or sets the list within a data source to monitor.
Public propertyDataSourceGets or sets the data source that the ErrorProvider monitors.
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Protected propertyEventsGets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public propertyIconGets or sets the Icon that is displayed next to a control when an error description string has been set for the control.
Public propertyRightToLeftGets or sets a value that indicates whether the component is used in a locale that supports right-to-left fonts.
Public propertySiteGets or sets the ISite of the Component. (Overrides Component.Site.)
Public propertyTagGets or sets an object that contains data about the component.
Top

  NameDescription
Public methodBindToDataAndErrorsProvides a method to set both the DataSource and DataMember at run time.
Public methodCanExtendGets a value indicating whether a control can be extended.
Public methodClearClears all settings associated with this component.
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodDisposeReleases all resources used by the Component. (Inherited from Component.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Overrides Component.Dispose(Boolean).)
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public methodGetErrorReturns the current error description string for the specified control.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetIconAlignmentGets a value indicating where the error icon should be placed in relation to the control.
Public methodGetIconPaddingReturns the amount of extra space to leave next to the error icon.
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected methodOnRightToLeftChangedRaises the RightToLeftChanged event.
Public methodSetErrorSets the error description string for the specified control.
Public methodSetIconAlignmentSets the location where the error icon should be placed in relation to the control.
Public methodSetIconPaddingSets the amount of extra space to leave between the specified control and the error icon.
Public methodToStringReturns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Public methodUpdateBindingProvides a method to update the bindings of the DataSource, DataMember, and the error text.
Top

  NameDescription
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public eventRightToLeftChangedOccurs when the RightToLeft property changes value.
Top

  NameDescription
Explicit interface implemetationPrivate methodISupportInitialize.BeginInitSignals the object that initialization is starting.
Explicit interface implemetationPrivate methodISupportInitialize.EndInitSignals the object that initialization is complete.
Top

ErrorProvider presents a simple mechanism for indicating to the end user that a control on a form has an error associated with it. If an error description string is specified for the control, an icon appears next to the control. The icon flashes in the manner specified by BlinkStyle, at the rate specified by BlinkRate. When the mouse hovers over the icon, a ToolTip appears showing the error description string.

Typically, you use ErrorProvider in association with data-bound controls. When using ErrorProvider with data-bound controls, you must specify the ContainerControl, either in the constructor or by setting the ContainerControl property.

NoteNote

The ErrorProvider component does not provide built-in support for accessibility clients. To make your application accessible when using this component, you must provide an additional, accessible feedback mechanism.

The following code example demonstrates using the ErrorProvider class to notify the user of a data entry error. The example creates a Form that contains a TextBox control, a NumericUpDown control, and a ComboBox control, each validating its content, and an ErrorProvider for each control. The example sets error icon options using the BlinkRate and BlinkStyle properties and the SetIconAlignment and SetIconPadding methods. The SetError method is called with or without appropriate error text during a control’s Validated event, depending upon the content in the control.

Imports System
Imports System.Drawing
Imports System.Windows.Forms

Namespace ErrorProvider

    Public NotInheritable Class Form1
        Inherits System.Windows.Forms.Form

        Private label1 As System.Windows.Forms.Label
        Private label2 As System.Windows.Forms.Label
        Private label3 As System.Windows.Forms.Label      
        Private label4 As System.Windows.Forms.Label
        Private label5 As System.Windows.Forms.Label
        Private label6 As System.Windows.Forms.Label
        Friend WithEvents favoriteColorComboBox As System.Windows.Forms.ComboBox 
        Friend WithEvents nameTextBox1 As System.Windows.Forms.TextBox 
        Friend WithEvents ageUpDownPicker As System.Windows.Forms.NumericUpDown      
        Private ageErrorProvider As System.Windows.Forms.ErrorProvider 
        Private nameErrorProvider As System.Windows.Forms.ErrorProvider 
        Private favoriteColorErrorProvider As System.Windows.Forms.ErrorProvider

        <System.STAThread()>  _
        Public Shared Sub Main()
            System.Windows.Forms.Application.Run(New Form1())
        End Sub 'Main

        Public Sub New()

            Me.nameTextBox1 = New System.Windows.Forms.TextBox()
            Me.label1 = New System.Windows.Forms.Label()
            Me.label2 = New System.Windows.Forms.Label()
            Me.ageUpDownPicker = New System.Windows.Forms.NumericUpDown()
            Me.favoriteColorComboBox = New System.Windows.Forms.ComboBox()
            Me.label3 = New System.Windows.Forms.Label()
            Me.label4 = New System.Windows.Forms.Label()
            Me.label5 = New System.Windows.Forms.Label()
            Me.label6 = New System.Windows.Forms.Label()

            ' Name Label 
            Me.label1.Location = New System.Drawing.Point(56, 32)
            Me.label1.Size = New System.Drawing.Size(40, 23)
            Me.label1.Text = "Name:" 

            ' Age Label 
            Me.label2.Location = New System.Drawing.Point(40, 64)
            Me.label2.Size = New System.Drawing.Size(56, 23)
            Me.label2.Text = "Age (3-5)" 

            ' Favorite Color Label 
            Me.label3.Location = New System.Drawing.Point(24, 96)
            Me.label3.Size = New System.Drawing.Size(80, 24)
            Me.label3.Text = "Favorite color" 

            ' ErrorBlinkStyle.AlwaysBlink Label 
            Me.label4.Location = New System.Drawing.Point(264, 32)
            Me.label4.Size = New System.Drawing.Size(160, 23)
            Me.label4.Text = "ErrorBlinkStyle.AlwaysBlink" 

            ' ErrorBlinkStyle.BlinkIfDifferentError Label 
            Me.label5.Location = New System.Drawing.Point(264, 64)
            Me.label5.Size = New System.Drawing.Size(200, 23)
            Me.label5.Text = "ErrorBlinkStyle.BlinkIfDifferentError" 

            ' ErrorBlinkStyle.NeverBlink Label 
            Me.label6.Location = New System.Drawing.Point(264, 96)
            Me.label6.Size = New System.Drawing.Size(200, 23)
            Me.label6.Text = "ErrorBlinkStyle.NeverBlink" 

            ' Name TextBox 
            Me.nameTextBox1.Location = New System.Drawing.Point(112, 32)
            Me.nameTextBox1.Size = New System.Drawing.Size(120, 20)
            Me.nameTextBox1.TabIndex = 0

            ' Age NumericUpDown 
            Me.ageUpDownPicker.Location = New System.Drawing.Point(112, 64)
            Me.ageUpDownPicker.Maximum = New System.Decimal(New Integer() {150, 0, 0, 0})
            Me.ageUpDownPicker.TabIndex = 4

            ' Favorite Color ComboBox 
            Me.favoriteColorComboBox.Items.AddRange(New Object() {"None", "Red", "Yellow", _
                                                                                    "Green", "Blue", "Purple"})
            Me.favoriteColorComboBox.Location = New System.Drawing.Point(112, 96)
            Me.favoriteColorComboBox.Size = New System.Drawing.Size(120, 21)
            Me.favoriteColorComboBox.TabIndex = 5

            ' Set up how the form should be displayed and add the controls to the form. 
            Me.ClientSize = New System.Drawing.Size(464, 150)
            Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.label6, Me.label5, Me.label4, _
                                          Me.label3, Me.favoriteColorComboBox, Me.ageUpDownPicker, Me.label2, _
                                          Me.label1, Me.nameTextBox1})

            Me.Text = "Error Provider Example" 

            ' Create and set the ErrorProvider for each data entry control.

            nameErrorProvider = New System.Windows.Forms.ErrorProvider()
            nameErrorProvider.SetIconAlignment(Me.nameTextBox1, ErrorIconAlignment.MiddleRight)
            nameErrorProvider.SetIconPadding(Me.nameTextBox1, 2)
            nameErrorProvider.BlinkRate = 1000
            nameErrorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.AlwaysBlink

            ageErrorProvider = New System.Windows.Forms.ErrorProvider()
            ageErrorProvider.SetIconAlignment(Me.ageUpDownPicker, ErrorIconAlignment.MiddleRight)
            ageErrorProvider.SetIconPadding(Me.ageUpDownPicker, 2)
            ageErrorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.BlinkIfDifferentError

            favoriteColorErrorProvider = New System.Windows.Forms.ErrorProvider()
            favoriteColorErrorProvider.SetIconAlignment(Me.favoriteColorComboBox, ErrorIconAlignment.MiddleRight)
            favoriteColorErrorProvider.SetIconPadding(Me.favoriteColorComboBox, 2)
            favoriteColorErrorProvider.BlinkRate = 1000
            favoriteColorErrorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink
        End Sub 'New 

        Private Sub nameTextBox1_Validated(sender As Object, e As System.EventArgs) Handles nameTextBox1.Validated
            If IsNameValid() Then 
                ' Clear the error, if any, in the error provider.
                nameErrorProvider.SetError(Me.nameTextBox1, String.Empty)
            Else 
                ' Set the error if the name is not valid.
                nameErrorProvider.SetError(Me.nameTextBox1, "Name is required.")
            End If  
        End Sub  

        Private Sub ageUpDownPicker_Validated(sender As Object, e As System.EventArgs) Handles ageUpDownPicker.Validated
            If IsAgeTooYoung() Then 
                ' Set the error if the age is too young.
                ageErrorProvider.SetError(Me.ageUpDownPicker, "Age not old enough")
            ElseIf IsAgeTooOld() Then 
                ' Set the error if the age is too old.
                ageErrorProvider.SetError(Me.ageUpDownPicker, "Age is too old")
            Else 
                ' Clear the error, if any, in the error provider.
                ageErrorProvider.SetError(Me.ageUpDownPicker, String.Empty)
            End If 
        End Sub 

        Private Sub favoriteColorComboBox_Validated(sender As Object, e As System.EventArgs) Handles favoriteColorComboBox.Validated
            If Not IsColorValid() Then 
                ' Set the error if the favorite color is not valid.
                favoriteColorErrorProvider.SetError(Me.favoriteColorComboBox, "Must select a color.")            
            Else 
                ' Clear the error, if any, in the error provider.
                favoriteColorErrorProvider.SetError(Me.favoriteColorComboBox, String.Empty)
            End If 
        End Sub  

        ' Functions to verify data. 
        Private Function IsNameValid() As Boolean 
            ' Determine whether the text box contains a zero-length string. 
            Return nameTextBox1.Text.Length > 0
        End Function  

        Private Function IsAgeTooYoung() As Boolean 
            ' Determine whether the age value is less than three. 
            Return ageUpDownPicker.Value < 3
        End Function  


        Private Function IsAgeTooOld() As Boolean 
            ' Determine whether the age value is greater than five. 
            Return ageUpDownPicker.Value > 5
        End Function  

        Private Function IsColorValid() As Boolean 
            ' Determine whether the favorite color has a valid value. 
            If (favoriteColorComboBox.SelectedItem IsNot Nothing) Then 
                    If Not(favoriteColorComboBox.SelectedItem.ToString().Equals("None")) Then 
                        Return true 
                    End If 
            End If 
            Return false
        End Function  

    End Class 'Form1
End Namespace 'ErrorProvider 

The following code example shows how to use the ErrorProvider with a DataSource and DataMember to indicate a data error to the user.

Private Sub InitializeComponent()
    ' Standard control setup. 
    '....                   
    ' You set the DataSource to a data set, and the DataMember to a table.
    errorProvider1.DataSource = dataSet1
    errorProvider1.DataMember = dataTable1.TableName
    errorProvider1.ContainerControl = Me
    errorProvider1.BlinkRate = 200
End Sub 'InitializeComponent
 '... 
' Since the ErrorProvider control does not have a visible component, 
' it does not need to be added to the form.  

Private Sub buttonSave_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    ' Checks for a bad post code. 
    Dim CustomersTable As DataTable
    CustomersTable = dataSet1.Tables("Customers")
    Dim row As DataRow
    For Each row In CustomersTable.Rows
        If Convert.ToBoolean(row("PostalCodeIsNull")) Then
            row.RowError = "The Customer details contain errors"
            row.SetColumnError("PostalCode", "Postal Code required")
        End If 
    Next row
End Sub 'buttonSave_Click

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft