天天看点

焦点事件中的Validating处理方法

有时候,我们需要检查用户输入到Windows窗体中的信息是否有效。例如,有一个电话号码的TextBox控件,需要检查该控件是否只包含适当的字符(数字、括号和连字符等等)。通常,我们可使用正则表达式验证用户输入的数据。

在了解Validating之前,还需要了解焦点事件的顺序,焦点事件按下列顺序发生:

Enter   //进入控件时发生

GotFocus   //在控件接收焦点时发生

Leave   //输入焦点离开控件时发生

Validating   //控件数据效验时发生

Validated  //数据效验完成后发生

LostFocus  //失去焦点时发生

        如果CausesValidation属性设置为false,则将取消Validating和Validated事件。GotFocus 和 LostFocus 事件是关联于 WM_KILLFOCUS 和 WM_SETFOCUS Windows 消息的低级别焦点事件。应对所有控件使用 Enter 和 Leave 事件。

        如果在 Validating 事件委托中,CancelEventArgs 对象的 Cancel 属性设置为 true,则正常情况下将在 Validating 事件之后发生的所有事件均被取消。

在操作中验证

要验证控件的内容,可以编写代码来处理 Validating 事件。在事件处理程序中,测试特定的条件(例如上面的电话号码)。验证是在处理时发生的一系列事件之一。

如果测试失败,则 Validating 事件的 CancelEventArgs 的 Cancel 属性将设置为 True。这将取消 Validating 事件,并导致焦点返回到控件(juky_huang注:这样会出现一个死循环,除非数据效验通过,可以使用下面强制方法来关闭)。实际的结果是,除非数据有效,否则用户将无法退出该控件。

关闭窗体和重写验证

当数据无效时,维护焦点的控件的副作用是,使用关闭窗体的任何常规方法都将无法关闭父窗体:

单击“关闭”框

通过右击标题栏显示的“系统”菜单

以编程方式调用 Close 方法

        不过,在某些情况下,无论控件中的值是否有效,您都希望用户可以关闭窗体。您可以重写验证,并通过创建窗体的 Closing 事件的处理程序来关闭仍包含无效数据的窗体。在该事件中,将 Cancel 属性设置为 False。这将强制关闭该窗体。

        如果使用此方法强制关闭窗体,控件中尚未保存的任何信息都将丢失。模式窗体在关闭时不会验证控件内容,仍可以使用控件验证将焦点锁定到控件,但不必考虑关闭窗体的行为。

以下是事例代码:

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

namespace MSDNValidatingEx

{

 /// <summary>

 /// Form1 的摘要说明。

 /// </summary>

 public class Form1 : System.Windows.Forms.Form

 {

  private System.Windows.Forms.TextBox textBox1;

  private System.Windows.Forms.ErrorProvider errorProvider1;

  /// <summary>

  /// 必需的设计器变量。

  /// </summary>

  private System.ComponentModel.Container components = null;

  public Form1()

  {

   //

   // Windows 窗体设计器支持所必需的

   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码

   InitializeComponent();

   textBox1.Validating+=new CancelEventHandler(textBox1_Validating); //给textBox1添加效验函数

   textBox1.Validated+=new EventHandler(textBox1_Validated);

  }

  private void textBox1_Validating(object sender,CancelEventArgs e)

   string errorMsg;

   if(!ValidEmailAddress(this.textBox1.Text,out errorMsg))

   {

    //如果效验没有通过取消后继事件,即Validated,LostFocus

    e.Cancel=true;

    this.textBox1.Select(0,this.textBox1.Text.Length);

    this.errorProvider1.SetError(this.textBox1,errorMsg);

   }

  private void textBox1_Validated(object sender,EventArgs e)

   errorProvider1.SetError(this.textBox1,"");

  public bool ValidEmailAddress(string emailAddress,out string errorMessage)

   //首先判断是否为空,然后判断是否有@,.符号

   if(emailAddress.Length==0)

    errorMessage="e-mail address is required.";

    return false;

   //是否包含@

   if(emailAddress.IndexOf("@")>-1)

    //从@往后面开始搜索,找到.的位置,如果位置大于@的位置说明格式正确

    if(emailAddress.IndexOf(".",emailAddress.IndexOf("@"))>emailAddress.IndexOf("@"))

    {

     errorMessage="";

     return true;

    }

   errorMessage="e-mail address must be valid e-mail address format.\n"+"For example '[email protected]'";

   return false;

  /// 清理所有正在使用的资源。

  protected override void Dispose( bool disposing )

   if( disposing )

    if (components != null)

     components.Dispose();

   base.Dispose( disposing );

  #region Windows 窗体设计器生成的代码

  /// 设计器支持所需的方法 - 不要使用代码编辑器修改

  /// 此方法的内容。

  private void InitializeComponent()

   this.textBox1 = new System.Windows.Forms.TextBox();

   this.errorProvider1 = new System.Windows.Forms.ErrorProvider();

   this.SuspendLayout();

   // textBox1

   this.textBox1.Location = new System.Drawing.Point(72, 88);

   this.textBox1.Name = "textBox1";

   this.textBox1.TabIndex = 0;

   this.textBox1.Text = "";

   // errorProvider1

   this.errorProvider1.ContainerControl = this;

   // Form1

   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

   this.ClientSize = new System.Drawing.Size(292, 273);

   this.Controls.Add(this.textBox1);

   this.Name = "Form1";

   this.Text = "Form1";

   this.ResumeLayout(false);

  #endregion

  /// 应用程序的主入口点。

  [STAThread]

  static void Main()

   Application.Run(new Form1());

 }

}

继续阅读