刚接触winform开发,为了实现一个简捷的数据验证制作了一个使用正则表达式验证数据的复合控件RegexTextBox
先帖张示例图
大家可以看到这就类似asp.net中验证控件的效果了,此控件提供6个关于数据验证的属性
刚接触winform开发,为了实现一个简捷的数据验证制作了一个使用正则表达式验证数据的复合控件RegexTextBox
先帖张示例图
大家可以看到这就类似asp.net中验证控件的效果了,此控件提供6个关于数据验证的属性
ErrorView,设置错误提示的样式
Expression,设置要匹配的正则表达式
IsAllowEmpty,设置控件的值是否允许为空
IsSelectAll,设置单击控件时是否全选其文本
KeepFocus,设置验证未通过时是否保持焦点,如果此项设为True,则未通过验证时鼠标焦点无法跳出此控件
SetError,设置验证未通过时提示的内容
控件大概的实现过程挺简单,后面提供全部源码(C#,VS2005,.Net Framework2.0)下载,有详细注释,还是在这里说一下,此控件继承自TextBox,在Validating,Click事件中使用正则表达式进行数据验证,不通过验证则在旁边按ErrorView属性设置来添加ErrorProvider控件或Label控件来显示SetError属性错误提示
下面是控件源码
RegexTextBox.cs
RegexTextBox.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MyControls
{
[System.ComponentModel.DefaultProperty("Expression")]
public partial class RegexTextBox : TextBox
{
public enum keepFocus//验证未通过时是否保持焦点;
{
False, True
}
private keepFocus _keepFocus = keepFocus.False;
private bool isValidated;//获取该控件是否已验证通过;
private bool isAllowEmpty = true;//设置控件的值是否允许为空;
private string expression = "";//设置要匹配的正则表达式;
private string setError = "";//验证未通过时提示的内容;
private bool isSelectAll = true;//设置单击控件时是否全选其文本;
private bool selectAlled = false;//获取和设置此控件的全选状态;
private System.Windows.Forms.ErrorProvider err = new ErrorProvider();
private System.Windows.Forms.Label label = new System.Windows.Forms.Label();
public enum errorView//设置错误提示的样式;
{
OnlyIco, OnlyText, Both
}
private errorView _errorView = errorView.OnlyIco;
public RegexTextBox()
{
InitializeComponent();
//添加事件
this.Validating += new System.ComponentModel.CancelEventHandler(RegexTextBox_Validating);
this.Click += new System.EventHandler(this.RegexTextBox_Click);
}
/**//// <summary>
/// 设置验证未通过时是否保持焦点
/// </summary>
[Browsable(true), Category("验证"), Description("设置验证未通过时是否保持焦点")]
public keepFocus KeepFocus
{
get { return _keepFocus; }
set
{
_keepFocus = value;
}
}
/**//// <summary>
/// 获取该控件是否已验证通过
/// </summary>
[Browsable(false), Category("验证"), Description("获取该控件是否已验证通过")]
public bool IsValidated
{
get { return isValidated; }
set { isValidated = value; }
}
/**//// <summary>
/// 设置控件的值是否允许为空
/// </summary>
[Browsable(true), Category("验证"), DefaultValue(true), Description("设置控件的值是否允许为空")]
public bool IsAllowEmpty
{
get { return isAllowEmpty; }
set { isAllowEmpty = value; }
}
/**//// <summary>
/// 设置要匹配的正则表达式
/// </summary>
[Browsable(true), Category("验证"), Description("设置要匹配的正则表达式")]
public string Expression
{
get { return expression; }
set { expression = value; }
}
/**//// <summary>
/// 设置验证未通过时提示的内容
/// </summary>
[Browsable(true), Category("验证"), Description("设置验证未通过时提示的内容")]
public string SetError
{
get { return setError; }
set { setError = value; }
}
/**//// <summary>
/// 设置单击控件时是否全选其文本
/// </summary>
[Browsable(true), Category("验证"), DefaultValue(true), Description("设置单击控件时是否全选其文本")]
public bool IsSelectAll
{
get { return isSelectAll; }
set { isSelectAll = value; }
}
/**//// <summary>
/// 获取和设置此控件的全选状态
/// </summary>
[Browsable(false), Category("验证"), DefaultValue(true), Description("获取和设置此控件的全选状态")]
public bool SelectAlled
{
get { return selectAlled; }
set { selectAlled = value; }
}
/**//// <summary>
/// 设置错误提示的样式
/// </summary>
[Browsable(true), Category("验证"), Description("设置错误提示的样式")]
public errorView ErrorView
{
get { return _errorView; }
set
{
_errorView = value;
}
}
/**//*
* 设置属性默认值
* 1.对于简单属性,使用DefaultValue();
* 2.对于复杂属性,使用Reset<属性名>,ShouldSerialize<属性名>来设置,VS只能识别这种命名格式的方法
* 设置了默认值,就应该相应的初始化这些属性
*/
public void ResetKeepFocus()
{
KeepFocus = keepFocus.False;
}
public bool ShouldSerializeKeepFocus()
{
return KeepFocus != keepFocus.False;
}
//
public void ResetErrorView()
{
ErrorView = errorView.OnlyIco;
}
public bool ShouldSerializeErrorView()
{
return ErrorView != errorView.OnlyIco;
}
public void RegexTextBox_Validating(object sender, CancelEventArgs e)
{
RegexTextBox t = (RegexTextBox)sender;
t.SelectAlled = false;
if (!System.Text.RegularExpressions.Regex.IsMatch(t.Text, expression) || (!isAllowEmpty && t.Text.Trim() == ""))
{
isValidated = false;
if (_errorView == errorView.OnlyIco)
{
IcoView(t);
}
if (_errorView == errorView.OnlyText)
{
TextView(t, 2);
}
if (_errorView == errorView.Both)
{
IcoView(t);
TextView(t, 22);
}
if (_keepFocus == keepFocus.True)
{
e.Cancel = true;
}
}
else
{
isValidated = true;
err.Clear();
this.Parent.Controls.Remove(label);
//err.SetError(this, "");
}
}
//显示ErrorProvider错误提示
private void IcoView(RegexTextBox t)
{
err.SetIconAlignment(t, ErrorIconAlignment.MiddleRight);
//err.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.AlwaysBlink;//错误图标一直闪烁,在这种情况下鼠标指上去的时候错误提示不会消失
err.SetIconPadding(t, 3);
err.SetError(t, setError == "" ? " " : setError);
}
//显示Label错误提示
private void TextView(RegexTextBox t, int pointX)
{
int x = t.Location.X + t.Size.Width + pointX;
int y = t.Location.Y + 6;
Point p = new Point(x, y);
label.AutoSize = true;
label.ForeColor = System.Drawing.Color.Red;
label.Font = new System.Drawing.Font("宋体", 10F);
label.BackColor = System.Drawing.Color.Transparent;
label.Location = p;
label.Text = setError;
t.Parent.Controls.Add(label);
}
private void RegexTextBox_Click(object sender, EventArgs e)
{
if (this.SelectAlled == false && IsSelectAll == true)
{
this.SelectAll();
this.SelectAlled = true;
}
}
protected override void OnPaint(PaintEventArgs pe)
{
// TODO: 在此处添加自定义绘制代码
// 调用基类 OnPaint
base.OnPaint(pe);
}
}
}
在说一下使用方法,此文刚开始的示例中button2的Click事件里要按范围来验证指定范围的RegexTextBox是否都已经通过了验证,这里的指定范围是指Control.ControlCollection类型的参数
private void button1_Click(object sender, EventArgs e)
{
BaseGlobals b = new BaseGlobals();
if (b.RegexTextBoxIsValidated(this.Controls))
{
MessageBox.Show("this.Controls通过");
}
}
BaseGlobals.cs的代码如下
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace Win
{
public class BaseGlobals
{
public BaseGlobals()
{}
private bool b = true;
/**//// <summary>
/// 递归遍历控件
/// </summary>
/// <param name="controls"></param>
/// <returns></returns>
private bool IsValidated(Control.ControlCollection controls)
{
foreach (System.Windows.Forms.Control ctl in controls)
{
//if (ctl.GetType()==typeof(NetHair.MyControls.RegexTextBox))//标准写法
if (ctl is MyControls.RegexTextBox)
{
MyControls.RegexTextBox rtxb = ctl as MyControls.RegexTextBox;
if (rtxb.IsValidated == false)
{
b = false;
rtxb.RegexTextBox_Validating(rtxb, new System.ComponentModel.CancelEventArgs());
}
}
else if (ctl.HasChildren)
{
IsValidated(ctl.Controls);
}
}
return b;
}
/**//// <summary>
/// 判断当前窗体上所有的RegexTextBox控件是否已验证通过
/// </summary>
public bool RegexTextBoxIsValidated(Control.ControlCollection controls)
{
b = true;
return IsValidated(controls);
}
}
}
好了到这里整个验证方案就完成了,每次有数据验证时只要按如下代码就可以了
BaseGlobals b = new BaseGlobals();
if (b.RegexTextBoxIsValidated(this.Controls))
{
MessageBox.Show("this.Controls通过");
}
提供此控件和示例全部源码下载RegexTextBox和示例(源码)环境C#,VS2005,.Net Framework2.0
刚接触winform开发,还请大家多给意见:)