焦点事件中的Validating处理方法

简介: 本文转载:http://tech.it168.com/oldarticle/2006-04-03/200604031055437.shtml 有时候,我们需要检查用户输入到Windows窗体中的信息是否有效。

本文转载:http://tech.it168.com/oldarticle/2006-04-03/200604031055437.shtml

有时候,我们需要检查用户输入到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 'someone@example.com'";
   return false;
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  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

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }
 }
}

 

目录
相关文章
|
2天前
|
弹性计算 运维 搜索推荐
三翼鸟携手阿里云ECS g9i:智慧家庭场景的效能革命与未来生活新范式
三翼鸟是海尔智家旗下全球首个智慧家庭场景品牌,致力于提供覆盖衣、食、住、娱的一站式全场景解决方案。截至2025年,服务近1亿家庭,连接设备超5000万台。面对高并发、低延迟与稳定性挑战,全面升级为阿里云ECS g9i实例,实现连接能力提升40%、故障率下降90%、响应速度提升至120ms以内,成本降低20%,推动智慧家庭体验全面跃迁。
|
3天前
|
数据采集 人工智能 自然语言处理
3分钟采集134篇AI文章!深度解析如何通过云无影AgentBay实现25倍并发 + LlamaIndex智能推荐
结合阿里云无影 AgentBay 云端并发采集与 LlamaIndex 智能分析,3分钟高效抓取134篇 AI Agent 文章,实现 AI 推荐、智能问答与知识沉淀,打造从数据获取到价值提炼的完整闭环。
351 91
|
10天前
|
人工智能 自然语言处理 前端开发
Qoder全栈开发实战指南:开启AI驱动的下一代编程范式
Qoder是阿里巴巴于2025年发布的AI编程平台,首创“智能代理式编程”,支持自然语言驱动的全栈开发。通过仓库级理解、多智能体协同与云端沙箱执行,实现从需求到上线的端到端自动化,大幅提升研发效率,重塑程序员角色,引领AI原生开发新范式。
851 156
|
3天前
|
数据采集 缓存 数据可视化
Android 无侵入式数据采集:从手动埋点到字节码插桩的演进之路
本文深入探讨Android无侵入式埋点技术,通过AOP与字节码插桩(如ASM)实现数据采集自动化,彻底解耦业务代码与埋点逻辑。涵盖页面浏览、点击事件自动追踪及注解驱动的半自动化方案,提升数据质量与研发效率,助力团队迈向高效、稳定的智能化埋点体系。(238字)
257 156
|
4天前
|
域名解析 人工智能
【实操攻略】手把手教学,免费领取.CN域名
即日起至2025年12月31日,购买万小智AI建站或云·企业官网,每单可免费领1个.CN域名首年!跟我了解领取攻略吧~
|
11天前
|
机器人 API 调度
基于 DMS Dify+Notebook+Airflow 实现 Agent 的一站式开发
本文提出“DMS Dify + Notebook + Airflow”三位一体架构,解决 Dify 在代码执行与定时调度上的局限。通过 Notebook 扩展 Python 环境,Airflow实现任务调度,构建可扩展、可运维的企业级智能 Agent 系统,提升大模型应用的工程化能力。
|
人工智能 前端开发 API
前端接入通义千问(Qwen)API:5 分钟实现你的 AI 问答助手
本文介绍如何在5分钟内通过前端接入通义千问(Qwen)API,快速打造一个AI问答助手。涵盖API配置、界面设计、流式响应、历史管理、错误重试等核心功能,并提供安全与性能优化建议,助你轻松集成智能对话能力到前端应用中。
816 154