ErrorProvider 类

定义

提供一个用户界面,用于指示窗体上的某个控件具有与其相关联的错误。

C#
public class ErrorProvider : System.ComponentModel.Component, System.ComponentModel.IExtenderProvider
C#
[System.ComponentModel.ComplexBindingProperties("DataSource", "DataMember")]
public class ErrorProvider : System.ComponentModel.Component, System.ComponentModel.IExtenderProvider, System.ComponentModel.ISupportInitialize
继承
属性
实现

示例

下面的代码示例演示如何使用 ErrorProvider 类通知用户数据输入错误。 该示例创建一个 Form ,其中包含一个 TextBox 控件、一个 NumericUpDown 控件和一个 ComboBox 控件,每个验证其内容,以及一个 ErrorProvider 用于每个控件的 。 该示例使用 BlinkRateBlinkStyle 属性以及 和 SetIconAlignmentSetIconPadding 方法设置错误图标选项。 在 SetError 控件 Validated 事件期间,调用 方法时带有或不包含相应的错误文本,具体取决于控件中的内容。

C#
using System;
using System.Drawing;
using System.Windows.Forms;

namespace ErrorProvider
{
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox nameTextBox1;
        private System.Windows.Forms.NumericUpDown ageUpDownPicker;
        private System.Windows.Forms.ComboBox favoriteColorComboBox;
        private System.Windows.Forms.ErrorProvider ageErrorProvider;
        private System.Windows.Forms.ErrorProvider nameErrorProvider;
        private System.Windows.Forms.ErrorProvider favoriteColorErrorProvider;

        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }

        public Form1()
        {
            this.nameTextBox1 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.ageUpDownPicker = new System.Windows.Forms.NumericUpDown();
            this.favoriteColorComboBox = new System.Windows.Forms.ComboBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();

            // Name Label
            this.label1.Location = new System.Drawing.Point(56, 32);
            this.label1.Size = new System.Drawing.Size(40, 23);
            this.label1.Text = "Name:";

            // Age Label
            this.label2.Location = new System.Drawing.Point(40, 64);
            this.label2.Size = new System.Drawing.Size(56, 23);
            this.label2.Text = "Age (3-5)";           

            // Favorite Color Label
            this.label3.Location = new System.Drawing.Point(24, 96);
            this.label3.Size = new System.Drawing.Size(80, 24);
            this.label3.Text = "Favorite color";

            // ErrorBlinkStyle.AlwaysBlink Label
            this.label4.Location = new System.Drawing.Point(264, 32);
            this.label4.Size = new System.Drawing.Size(160, 23);
            this.label4.Text = "ErrorBlinkStyle.AlwaysBlink";

            // ErrorBlinkStyle.BlinkIfDifferentError Label
            this.label5.Location = new System.Drawing.Point(264, 64);
            this.label5.Size = new System.Drawing.Size(200, 23);
            this.label5.Text = "ErrorBlinkStyle.BlinkIfDifferentError";

            // ErrorBlinkStyle.NeverBlink Label
            this.label6.Location = new System.Drawing.Point(264, 96);
            this.label6.Size = new System.Drawing.Size(200, 23);
            this.label6.Text = "ErrorBlinkStyle.NeverBlink";

            // Name TextBox
            this.nameTextBox1.Location = new System.Drawing.Point(112, 32);
            this.nameTextBox1.Size = new System.Drawing.Size(120, 20);
            this.nameTextBox1.TabIndex = 0;
            this.nameTextBox1.Validated += new System.EventHandler(this.nameTextBox1_Validated);

            // Age NumericUpDown
            this.ageUpDownPicker.Location = new System.Drawing.Point(112, 64);
            this.ageUpDownPicker.Maximum = new System.Decimal(new int[] {150,0,0,0});
            this.ageUpDownPicker.TabIndex = 4;
            this.ageUpDownPicker.Validated += new System.EventHandler(this.ageUpDownPicker_Validated);

            // Favorite Color ComboBox
            this.favoriteColorComboBox.Items.AddRange(new object[] {"None","Red","Yellow",
                                                                    "Green","Blue","Purple"});
            this.favoriteColorComboBox.Location = new System.Drawing.Point(112, 96);
            this.favoriteColorComboBox.Size = new System.Drawing.Size(120, 21);
            this.favoriteColorComboBox.TabIndex = 5;
            this.favoriteColorComboBox.Validated += new System.EventHandler(this.favoriteColorComboBox_Validated);

            // Set up how the form should be displayed and add the controls to the form.
            this.ClientSize = new System.Drawing.Size(464, 150);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                        this.label6,this.label5,this.label4,this.label3,
                                        this.favoriteColorComboBox,this.ageUpDownPicker,
                                        this.label2,this.label1,this.nameTextBox1});
            this.Text = "Error Provider Example";

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

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

            ageErrorProvider = new  System.Windows.Forms.ErrorProvider();
            ageErrorProvider.SetIconAlignment (this.ageUpDownPicker, ErrorIconAlignment.MiddleRight);
            ageErrorProvider.SetIconPadding (this.ageUpDownPicker, 2);
            ageErrorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.BlinkIfDifferentError;

            favoriteColorErrorProvider = new  System.Windows.Forms.ErrorProvider();
            favoriteColorErrorProvider.SetIconAlignment (this.favoriteColorComboBox, ErrorIconAlignment.MiddleRight);
            favoriteColorErrorProvider.SetIconPadding (this.favoriteColorComboBox, 2);
            favoriteColorErrorProvider.BlinkRate = 1000;
            favoriteColorErrorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;
        }
    
        private void nameTextBox1_Validated(object sender, System.EventArgs e)
        {
            if(IsNameValid())
            {
                // Clear the error, if any, in the error provider.
                nameErrorProvider.SetError(this.nameTextBox1, String.Empty);
            }
            else
            {
                // Set the error if the name is not valid.
                nameErrorProvider.SetError(this.nameTextBox1, "Name is required.");
            }
        }

        private void ageUpDownPicker_Validated(object sender, System.EventArgs e)
        {
            if (IsAgeTooYoung())
            {
                // Set the error if the age is too young.
                ageErrorProvider.SetError(this.ageUpDownPicker, "Age not old enough");
            }
            else if (IsAgeTooOld())
            {
                // Set the error if the age is too old.
                ageErrorProvider.SetError(this.ageUpDownPicker, "Age is too old");
            }
            else 
            {
                // Clear the error, if any, in the error provider.
                ageErrorProvider.SetError(this.ageUpDownPicker, String.Empty);
            }
        }

        private void favoriteColorComboBox_Validated(object sender, System.EventArgs e) 
        {
            if (!IsColorValid())
            {
                // Set the error if the favorite color is not valid.
                favoriteColorErrorProvider.SetError(this.favoriteColorComboBox, "Must select a color.");
            }
            else
            {
                // Clear the error, if any, in the error provider.
                favoriteColorErrorProvider.SetError(this.favoriteColorComboBox, String.Empty);
            }
        }

        // Functions to verify data.
        private bool IsNameValid() 
        {
            // Determine whether the text box contains a zero-length string.
            return (nameTextBox1.Text.Length > 0);
        }

        private bool IsAgeTooYoung() 
        {
            // Determine whether the age value is less than three.
            return (ageUpDownPicker.Value < 3);
        }

        private bool IsAgeTooOld() 
        {
            // Determine whether the age value is greater than five.
            return (ageUpDownPicker.Value > 5 );
        }

        private bool IsColorValid() 
        {
            // Determine whether the favorite color has a valid value.
            return ((favoriteColorComboBox.SelectedItem != null) &&
                (!favoriteColorComboBox.SelectedItem.ToString().Equals("None")));
        }
    }
}

下面的代码示例演示如何将 ErrorProvider 与 一起使用 DataSource ,并 DataMember 向用户指示数据错误。

C#
private void 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 = this ;
     errorProvider1.BlinkRate = 200 ;
     //...
     // Since the ErrorProvider control does not have a visible component,
     // it does not need to be added to the form. 
 }
 
 private void buttonSave_Click(object sender, System.EventArgs e)
 {
     // Checks for a bad post code.
     DataTable CustomersTable;
     CustomersTable = dataSet1.Tables["Customers"];
     foreach (DataRow row in (CustomersTable.Rows)) 
     {
         if (Convert.ToBoolean(row["PostalCodeIsNull"])) 
         {
             row.RowError="The Customer details contain errors";
             row.SetColumnError("PostalCode", "Postal Code required");
         } 
     } 
 }

注解

ErrorProvider 提供了一种简单机制,用于向最终用户指示窗体上的控件具有与之关联的错误。 如果为控件指定了错误说明字符串,则控件旁边会显示一个图标。 图标以 指定 BlinkStyle的方式以 指定的 BlinkRate速率闪烁。 当鼠标悬停在图标上时,将显示一个工具提示,其中显示了错误说明字符串。

通常,使用 ErrorProvider 与数据绑定控件相关联。 与数据绑定控件一起使用ErrorProvider时,必须在构造函数中或通过设置 ContainerControl 属性来指定 ContainerControl

备注

ErrorProvider 组件不提供对辅助功能客户端的内置支持。 若要使应用程序在使用此组件时可供访问,必须提供其他可访问的反馈机制。

构造函数

ErrorProvider()

初始化 ErrorProvider 类的新实例并初始化 BlinkRateBlinkStyleIcon 的默认设置。

ErrorProvider(ContainerControl)

初始化附加到容器的 ErrorProvider 类的新实例。

ErrorProvider(IContainer)

初始化附加到 ErrorProvider 实现的 IContainer 类的新实例。

属性

BlinkRate

获取或设置错误图标的闪烁速率。

BlinkStyle

获取或设置一个值,通过该值指示错误图标的闪烁时间。

CanRaiseEvents

获取一个指示组件是否可以引发事件的值。

(继承自 Component)
Container

获取包含 IContainerComponent

(继承自 Component)
ContainerControl

获取或设置一个值,通过该值指示此 ErrorProvider 的父控件。

DataMember

获取或设置数据源中要监视的列表。

DataSource

获取或设置 ErrorProvider 监视的数据源。

DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。

(继承自 Component)
Events

获取附加到此 Component 的事件处理程序的列表。

(继承自 Component)
HasErrors

获取一个值,该值指示这 ErrorProvider 是否对任何关联的控件有任何错误。

Icon

获取或设置 Icon,当为控件设置了错误描述字符串时,该图标显示在控件旁边。

RightToLeft

获取或设置一个值,该值指示组件是否可用于支持从右向左字体的区域设置。

Site

获取或设置 ComponentISite

Tag

获取或设置包含有关组件的数据的对象。

方法

BindToDataAndErrors(Object, String)

提供在运行时同时设置 DataSourceDataMember 的方法。

CanExtend(Object)

获取一个值,通过该值指示控件是否可以扩展。

Clear()

清除与此组件关联的所有设置。

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。

(继承自 MarshalByRefObject)
Dispose()

释放由 Component 使用的所有资源。

(继承自 Component)
Dispose(Boolean)

释放由 Component 占用的非托管资源,还可以另外再释放托管资源。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetError(Control)

返回指定控件的当前错误描述字符串。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetIconAlignment(Control)

获取一个值,通过该值指示错误图标相对于控件的放置位置。

GetIconPadding(Control)

返回错误图标旁边保留的额外空间量。

GetLifetimeService()
已过时.

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。

(继承自 Component)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
OnRightToLeftChanged(EventArgs)

引发 RightToLeftChanged 事件。

SetError(Control, String)

设置指定控件的错误描述字符串。

SetIconAlignment(Control, ErrorIconAlignment)

设置错误图标相对于控件的放置位置。

SetIconPadding(Control, Int32)

设置指定控件和错误图标之间应保留的额外空间量。

ToString()

返回包含 Component 的名称的 String(如果有)。 不应重写此方法。

(继承自 Component)
UpdateBinding()

提供更新 DataSourceDataMember 和错误文本的绑定的方法。

事件

Disposed

在通过调用 Dispose() 方法释放组件时发生。

(继承自 Component)
RightToLeftChanged

RightToLeft 属性值更改时发生。

显式接口实现

ISupportInitialize.BeginInit()

用信号通知对象初始化即将开始。

ISupportInitialize.EndInit()

用信号通知对象初始化已完成。

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10