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

一个只能输入数值型数据的文本框类实现(C#)

2007-03-13 23:00 627 查看
在软件开发时,经常面临数值类型数据的输入,如和限定文本框只能输入数值型数据,是一件麻烦事情。开发一个只能输入数值型数据的文本框可以简化很多开发工作,其代码如下,供参考。

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace PRisk
{
class TextBoxForDigit:TextBox
{
public ToolTip toolTip=new ToolTip() ;
public double max;
public double min;
public string tip = "输入数字型数据";
public TextBoxForDigit()
{
this.Validating +=
new System.ComponentModel.CancelEventHandler(NumberValidating);
this.MouseHover += new System.EventHandler(mMouseHover);

toolTip.SetToolTip(this , tip);

}
private void NumberValidating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!CheckIfTextBoxNumeric((TextBox)sender))
{
// myLabel.Text = "Has to be numeric";
e.Cancel = true;
}
}
private void mMouseHover(object sender, EventArgs e)
{
toolTip.SetToolTip(this, "输入数字型数据");
}

private bool CheckIfTextBoxNumeric(TextBox textBox)
{
bool isValid = true;
int pointCount = 0, negativeCount = 0;
if (textBox.Text == "")//判断是否为空
{
isValid = false; return isValid;

}
char ch;
for (int i = 0; i < textBox.Text.Length; i++)
{
ch = textBox.Text[i];

if (!System.Char.IsDigit(ch))
{
if (ch == '.') //如果是小数点
{
pointCount++;
if (i == 0 || i == textBox.Text.Length - 1)//如果在开始或结尾
{
textBox.Text = ""; isValid = false; return isValid;
}

}
if (ch == '-') //如果是负号
{
negativeCount++;
if (i!=0)//如果不在开始
{
textBox.Text = ""; isValid = false; return isValid;
}
}
if (ch != '-' && ch != '.')
{ textBox.Text = ""; isValid = false; return isValid; }

}
}
if (negativeCount > 1 || pointCount > 1)
{ textBox.Text = ""; isValid = false; return isValid; }
return isValid;

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐