C# WinForm 文本框只能输入带两位小数的数字
时间:2010-09-20 来源:游虫
之前的做法是:
if (!(char.IsNumber(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == (char)('.')))
{
e.Handled = true;
}
但这种方式存在一些问题,例如可以输入两个小数。。。
后来改用正则表达式加上面的代码来处理:
先using:
using System.Text.RegularExpressions;
代码:
private void amountTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (Convert.ToInt32(e.KeyChar) == 8)
{
e.Handled = false;
}
else
{
Regex rex = new Regex(@"^[0-9.]*$"); //初始化正则表达式(检测每次输入的字符)
Regex rexFull = new Regex(@"^[0-9]+(.[0-9]{0,1})?$"); //初始化正则表达式(检测所有已经输入的字符)
if (rexFull.IsMatch(this.amountTextBox.Text.Trim()) || rexFull.IsMatch(this.amountTextBox.Text.Trim() + e.KeyChar.ToString()))
{
if (Regex.Matches(this.amountTextBox.Text.Trim() + e.KeyChar.ToString(), "\\.").Count == 2) //防止输入两个小数点
{
e.Handled = true;
}
else
{
if (!(char.IsNumber(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == (char)('.')))
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
}
else
{
e.Handled = true;
}
}
}
这样可以解决问题,但依然存在一个之前也存在的问题,那就是当文本框没内容时,鼠标点其他地方都没任何反应,类似于假死。。。
没办法,只好加个默认值了:
private void amountTextBox_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.amountTextBox.Text.Trim()))
{
this.amountTextBox.Text = "20";
this.amountTextBox.SelectAll();
}
else if (this.amountTextBox.Text.Trim().Substring(0, 1) == ".")
{
this.amountTextBox.Text = this.amountTextBox.Text.Trim().Substring(1, this.amountTextBox.Text.Trim().Length - 1);
}
}
到这里面问题基本上都解决了,但感觉太麻烦了,不知道大家有没有更好的解决方法!
相关阅读 更多 +