方便winform中的数据验证,制作一个使用正则表达式验证数据的复合控件

刚接触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

ContractedBlock.gif ExpandedBlockStart.gif RegexTextBox.cs
None.gifusing System;
None.gif
using System.Collections.Generic;
None.gif
using System.ComponentModel;
None.gif
using System.Data;
None.gif
using System.Drawing;
None.gif
using System.Text;
None.gif
using System.Windows.Forms;
None.gif
None.gif
namespace MyControls
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    [System.ComponentModel.DefaultProperty(
"Expression")]
InBlock.gif    
public partial class RegexTextBox : TextBox
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public enum keepFocus//验证未通过时是否保持焦点;
ExpandedSubBlockStart.gifContractedSubBlock.gif
        dot.gif{
InBlock.gif            False, True
ExpandedSubBlockEnd.gif        }

InBlock.gif        
private keepFocus _keepFocus = keepFocus.False;
InBlock.gif        
private bool isValidated;//获取该控件是否已验证通过;
InBlock.gif
        private bool isAllowEmpty = true;//设置控件的值是否允许为空;
InBlock.gif
        private string expression = "";//设置要匹配的正则表达式;
InBlock.gif
        private string setError = "";//验证未通过时提示的内容;
InBlock.gif
        private bool isSelectAll = true;//设置单击控件时是否全选其文本;
InBlock.gif
        private bool selectAlled = false;//获取和设置此控件的全选状态;
InBlock.gif
        private System.Windows.Forms.ErrorProvider err = new ErrorProvider();
InBlock.gif        
private System.Windows.Forms.Label label = new System.Windows.Forms.Label();
InBlock.gif        
public enum errorView//设置错误提示的样式;
ExpandedSubBlockStart.gifContractedSubBlock.gif
        dot.gif{
InBlock.gif            OnlyIco, OnlyText, Both
ExpandedSubBlockEnd.gif        }

InBlock.gif        
private errorView _errorView = errorView.OnlyIco;
InBlock.gif
InBlock.gif
InBlock.gif        
public RegexTextBox()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            InitializeComponent();
InBlock.gif            
//添加事件
InBlock.gif
            this.Validating += new System.ComponentModel.CancelEventHandler(RegexTextBox_Validating);
InBlock.gif            
this.Click += new System.EventHandler(this.RegexTextBox_Click);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 设置验证未通过时是否保持焦点
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [Browsable(true), Category("验证"), Description("设置验证未通过时是否保持焦点")]
InBlock.gif        
public keepFocus KeepFocus
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn _keepFocus; }
InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _keepFocus 
= value;
ExpandedSubBlockEnd.gif            }

InBlock.gif
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获取该控件是否已验证通过
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [Browsable(false), Category("验证"), Description("获取该控件是否已验证通过")]
InBlock.gif        
public bool IsValidated
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn isValidated; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ isValidated = value; }
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 设置控件的值是否允许为空
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [Browsable(true), Category("验证"), DefaultValue(true), Description("设置控件的值是否允许为空")]
InBlock.gif        
public bool IsAllowEmpty
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn isAllowEmpty; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ isAllowEmpty = value; }
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 设置要匹配的正则表达式
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [Browsable(true), Category("验证"), Description("设置要匹配的正则表达式")]
InBlock.gif        
public string Expression
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn expression; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ expression = value; }
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 设置验证未通过时提示的内容
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [Browsable(true), Category("验证"), Description("设置验证未通过时提示的内容")]
InBlock.gif        
public string SetError
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn setError; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ setError = value; }
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 设置单击控件时是否全选其文本
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [Browsable(true), Category("验证"), DefaultValue(true), Description("设置单击控件时是否全选其文本")]
InBlock.gif        
public bool IsSelectAll
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn isSelectAll; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ isSelectAll = value; }
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获取和设置此控件的全选状态
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [Browsable(false), Category("验证"), DefaultValue(true), Description("获取和设置此控件的全选状态")]
InBlock.gif        
public bool SelectAlled
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn selectAlled; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ selectAlled = value; }
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 设置错误提示的样式
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [Browsable(true), Category("验证"), Description("设置错误提示的样式")]
InBlock.gif        
public errorView ErrorView
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn _errorView; }
InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _errorView 
= value;
ExpandedSubBlockEnd.gif            }

InBlock.gif
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//*
InBlock.gif         * 设置属性默认值
InBlock.gif         * 1.对于简单属性,使用DefaultValue();
InBlock.gif         * 2.对于复杂属性,使用Reset<属性名>,ShouldSerialize<属性名>来设置,VS只能识别这种命名格式的方法
InBlock.gif         * 设置了默认值,就应该相应的初始化这些属性
ExpandedSubBlockEnd.gif         
*/

InBlock.gif        
public void ResetKeepFocus()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            KeepFocus 
= keepFocus.False;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public bool ShouldSerializeKeepFocus()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return KeepFocus != keepFocus.False;
ExpandedSubBlockEnd.gif        }

InBlock.gif        
//
InBlock.gif
        public void ResetErrorView()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ErrorView 
= errorView.OnlyIco;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public bool ShouldSerializeErrorView()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return ErrorView != errorView.OnlyIco;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public void RegexTextBox_Validating(object sender, CancelEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            RegexTextBox t 
= (RegexTextBox)sender;
InBlock.gif            t.SelectAlled 
= false;
InBlock.gif            
if (!System.Text.RegularExpressions.Regex.IsMatch(t.Text, expression) || (!isAllowEmpty && t.Text.Trim() == ""))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                isValidated 
= false;
InBlock.gif
InBlock.gif                
if (_errorView == errorView.OnlyIco)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    IcoView(t);
ExpandedSubBlockEnd.gif                }

InBlock.gif                
if (_errorView == errorView.OnlyText)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    TextView(t, 
2);
ExpandedSubBlockEnd.gif                }

InBlock.gif                
if (_errorView == errorView.Both)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    IcoView(t);
InBlock.gif                    TextView(t, 
22);
ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif                
if (_keepFocus == keepFocus.True)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    e.Cancel 
= true;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                isValidated 
= true;
InBlock.gif                err.Clear();
InBlock.gif                
this.Parent.Controls.Remove(label);
InBlock.gif                
//err.SetError(this, "");
ExpandedSubBlockEnd.gif
            }

ExpandedSubBlockEnd.gif        }

InBlock.gif        
//显示ErrorProvider错误提示
InBlock.gif
        private void IcoView(RegexTextBox t)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            err.SetIconAlignment(t, ErrorIconAlignment.MiddleRight);
InBlock.gif            
//err.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.AlwaysBlink;//错误图标一直闪烁,在这种情况下鼠标指上去的时候错误提示不会消失
InBlock.gif
            err.SetIconPadding(t, 3);
InBlock.gif            err.SetError(t, setError 
== "" ? " " : setError);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
//显示Label错误提示
InBlock.gif
        private void TextView(RegexTextBox t, int pointX)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int x = t.Location.X + t.Size.Width + pointX;
InBlock.gif            
int y = t.Location.Y + 6;
InBlock.gif            Point p 
= new Point(x, y);
InBlock.gif
InBlock.gif            label.AutoSize 
= true;
InBlock.gif            label.ForeColor 
= System.Drawing.Color.Red;
InBlock.gif            label.Font 
= new System.Drawing.Font("宋体", 10F);
InBlock.gif            label.BackColor 
= System.Drawing.Color.Transparent;
InBlock.gif            label.Location 
= p;
InBlock.gif            label.Text 
= setError;
InBlock.gif            t.Parent.Controls.Add(label);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void RegexTextBox_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (this.SelectAlled == false && IsSelectAll == true)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
this.SelectAll();
InBlock.gif                
this.SelectAlled = true;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif        
protected override void OnPaint(PaintEventArgs pe)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// TODO: 在此处添加自定义绘制代码
InBlock.gif
InBlock.gif            
// 调用基类 OnPaint
InBlock.gif
            base.OnPaint(pe);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif


在说一下使用方法,此文刚开始的示例中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的代码如下

 

ContractedBlock.gif ExpandedBlockStart.gif
None.gifusing System;
None.gif
using System.Collections.Generic;
None.gif
using System.Text;
None.gif
using System.Windows.Forms;
None.gif
None.gif
namespace Win
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
public class BaseGlobals
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public BaseGlobals()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{}
InBlock.gif        
private bool b = true;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 递归遍历控件
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="controls"></param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        private bool IsValidated(Control.ControlCollection controls)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
foreach (System.Windows.Forms.Control ctl in controls)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//if (ctl.GetType()==typeof(NetHair.MyControls.RegexTextBox))//标准写法
InBlock.gif
                if (ctl is MyControls.RegexTextBox)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    MyControls.RegexTextBox rtxb 
= ctl as MyControls.RegexTextBox;
InBlock.gif                    
if (rtxb.IsValidated == false)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        b 
= false;
InBlock.gif                        rtxb.RegexTextBox_Validating(rtxb, 
new System.ComponentModel.CancelEventArgs());
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif                
else if (ctl.HasChildren)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    IsValidated(ctl.Controls);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return b;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 判断当前窗体上所有的RegexTextBox控件是否已验证通过
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public bool RegexTextBoxIsValidated(Control.ControlCollection controls)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            b 
= true;
InBlock.gif            
return IsValidated(controls);
ExpandedSubBlockEnd.gif        }
  
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}

None.gif

 

好了到这里整个验证方案就完成了,每次有数据验证时只要按如下代码就可以了

BaseGlobals b = new BaseGlobals();
            if (b.RegexTextBoxIsValidated(this.Controls))
            {
                MessageBox.Show("this.Controls通过");
            }

提供此控件和示例全部源码下载RegexTextBox和示例(源码)环境C#,VS2005,.Net Framework2.0

刚接触winform开发,还请大家多给意见:)

转载于:https://www.cnblogs.com/dikongpulu/archive/2007/09/18/897375.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值