本人的意思是只能输入数字,结果负号和小数点都不能输入了,晕。
哪里有问题?
哪里有问题?
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != "\b")
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"^(-?\d+)(\.\d+)?$"))
{
e.Handled = true;
}
}
}
解决方案
40
你这个输单个字符,正则匹配的是整体
不需要正则
不需要正则
public static bool NumberDotTextbox_KeyPress(object sender, KeyPressEventArgs e)
{
//允许输入数字、小数点、删除键和负号
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)(".") && e.KeyChar != (char)("-"))
{
return true;
}
if (e.KeyChar == (char)("-"))
{
if ((sender as TextBox).Text != "")
{
return true;
}
}
//小数点只能输入一次
if (e.KeyChar == (char)(".") && ((TextBox)sender).Text.IndexOf(".") != -1)
{
return true;
}
//第一位不能为小数点
if (e.KeyChar == (char)(".") && ((TextBox)sender).Text == "")
{
return true;
}
//第一位是0,第二位必须为小数点
if (e.KeyChar != (char)(".") && e.KeyChar != 8 && ((TextBox)sender).Text == "0")
{
return true;
}
//第一位是负号,第二位不能为小数点
if (((TextBox)sender).Text == "-" && e.KeyChar == (char)("."))
{
return true;
}
return false;
}