如何:使用 Windows 窗体 ErrorProvider 组件显示窗体验证的错误图标

当用户输入无效数据时,可以使用 Windows 窗体 ErrorProvider 组件显示错误图标。 窗体上必须至少有两个控件,才能在它们之间按 Tab 键,从而调用验证代码。

当控件的值无效时显示错误图标

  1. 将两个控件(例如文本框)添加到 Windows 窗体。

  2. ErrorProvider 组件添加到窗体。

  3. 选择第一个控件并将代码添加到其 Validating 事件处理程序。 为了使此代码正常运行,该过程必须连接到事件。 有关详细信息,请参阅如何:在运行时为 Windows 窗体创建事件处理程序

    以下代码测试用户输入的数据的有效性;如果数据无效,则调用 SetError 方法。 SetError 方法的第一个参数指定要显示旁边图标的控件。 第二个参数是要显示的错误文本。

    Private Sub TextBox1_Validating(ByVal Sender As Object, _
       ByVal e As System.ComponentModel.CancelEventArgs) Handles _
       TextBox1.Validating
          If Not IsNumeric(TextBox1.Text) Then
             ErrorProvider1.SetError(TextBox1, "Not a numeric value.")
          Else
             ' Clear the error.
             ErrorProvider1.SetError(TextBox1, "")
          End If
    End Sub
    
    protected void textBox1_Validating (object sender,
       System.ComponentModel.CancelEventArgs e)
    {
       try
       {
          int x = Int32.Parse(textBox1.Text);
          errorProvider1.SetError(textBox1, "");
       }
       catch (Exception ex)
       {
          errorProvider1.SetError(textBox1, "Not an integer value.");
       }
    }
    
    private:
       System::Void textBox1_Validating(System::Object ^  sender,
          System::ComponentModel::CancelEventArgs ^  e)
       {
          try
          {
             int x = Int32::Parse(textBox1->Text);
             errorProvider1->SetError(textBox1, "");
          }
          catch (System::Exception ^ ex)
          {
             errorProvider1->SetError(textBox1, "Not an integer value.");
          }
       }
    

    (Visual C#、Visual C++)将以下代码置于表单的构造函数中以注册事件处理程序。

    this.textBox1.Validating += new
    System.ComponentModel.CancelEventHandler(this.textBox1_Validating);
    
    this->textBox1->Validating += gcnew
       System::ComponentModel::CancelEventHandler
       (this, &Form1::textBox1_Validating);
    
  4. 启动项目。 在第一个控件中键入无效(在此示例中,非数字)数据,然后按 Tab 键进入第二个控件。 显示错误图标时,使用鼠标指针指向它以查看错误文本。

另请参阅