您的位置:首页 > 编程语言 > C#

[C#]重写文本控件的OnKeyPress和OnTextChanged进行录入数据校验

2006-01-05 18:32 357 查看
//记录OnKeyPress前的字符
string BeforKeyPressText = "";
//记录OnKeyPress执行时输入被视为无效(e.Handled = true;)的次数 注:一个汉字和一个英文字母的输入各执行一次OnKeyPress
int ErrKeyPressNum = 0;
/// <summary>
/// 实现输入控制:字符过滤
/// by arming 2005-11-28
/// </summary>
/// <param name="e"></param>
protected override void OnKeyPress(KeyPressEventArgs e)
{
//取出击键前的文本框文本
BeforKeyPressText = this.Text;
string[] regexExpressions=new string[2];
regexExpressions= (string[])CommonDataDefine.HtDTRE()[this.InputType.ToString()];
Regex regex = new Regex(regexExpressions[0]);
Match m = regex.Match(e.KeyChar.ToString());
if(!m.Success)
{
e.Handled = true;
//被处理为无效输入
++ErrKeyPressNum;
}
base.OnKeyPress (e);
}
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected override void OnTextChanged(EventArgs e)
{
if( ErrKeyPressNum > 1 )
{
--ErrKeyPressNum;
return;
}
if( ErrKeyPressNum == 1 )
{
--ErrKeyPressNum;
this.Text = BeforKeyPressText;
this.Select(BeforKeyPressText.Length,0);
}

if(this.InputType.ToString()=="Decimal4"&&this.Text.Trim()!=""&&this.Text.Trim()!="-")
{
try
{
decimal inputDecimal = System.Convert.ToDecimal(this.Text.Trim());
//数字长度
int p = this.MaxLength;
//小数点位置
int d1 = BeforKeyPressText.IndexOf('.');
int d2 = this.Text.Trim().IndexOf('.');
//
if(d2==-1&&this.Text.Trim().Length>p-4)
{
this.Text = BeforKeyPressText;
this.Select(BeforKeyPressText.Length,0);
}
else if(d2!=-1&&(this.Text.Trim().Length-d2-1>4||d2>p-4))
{
this.Text = BeforKeyPressText;
this.Select(BeforKeyPressText.Length,0);
}
}
catch
{
this.Text = BeforKeyPressText;
this.Select(BeforKeyPressText.Length,0);
}
}
//整数 判断输入是否大于或小于Int所能保存的数值范围
if((this.InputType.ToString()=="Number"||this.InputType.ToString()=="Int")&&this.Text.Trim()!=""&&this.Text.Trim()!="-")
{
try
{
int inputNum = System.Convert.ToInt32(this.Text.Trim());
}
catch
{
this.Text = BeforKeyPressText;
this.Select(BeforKeyPressText.Length,0);
}
}
//有两位小数点的小数 如Decimal(12,2)
if(this.InputType.ToString()=="Decimal"&&this.Text.Trim()!=""&&this.Text.Trim()!="-")
{
try
{
decimal inputDecimal = System.Convert.ToDecimal(this.Text.Trim());
//数字长度
int p = this.MaxLength;
//小数点位置
int d1 = BeforKeyPressText.IndexOf('.');
int d2 = this.Text.Trim().IndexOf('.');

if(d2==-1&&this.Text.Trim().Length>p-2)
{
this.Text = BeforKeyPressText;
this.Select(BeforKeyPressText.Length,0);
}
else if(d2!=-1&&(this.Text.Trim().Length-d2-1>2||d2>p-2))
{
this.Text = BeforKeyPressText;
this.Select(BeforKeyPressText.Length,0);
}
}
catch
{
this.Text = BeforKeyPressText;
this.Select(BeforKeyPressText.Length,0);
}
}

base.OnTextChanged (e);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: