由于项目需要,需要写一个TextBox文本框,此文本框需要满足:只能输入正数,负数和小数。比如:3,0.3,-4,-0.4等等。
在网上找了许多正则表达式都不好用,由于本人又对正则表达式一窍不通,就换了一种方式。使用了TextBox的KeyPress事件,完成了上述需求。这点代码写了一下午有木有,下面分享给大家。
代码如下:
C#代码
/*
*设置textBox只能输入数字(正数,负数,小数)
*/
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//允许输入数字、小数点、删除键和负号
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e.KeyChar != (char)('-'))
{
MessageBox.Show("请输入正确的数字");
this.textBox1.Text = "";
e.Handled = true;
}
if (e.KeyChar == (char)('-'))
{
if (textBox1.Text != "")
{
MessageBox.Show("请输入正确的数字");
this.textBox1.Text = "";
e.Handled = true;
}
}
//小数点只能输入一次
if (e.KeyChar == (char)('.') && ((TextBox)sender).Text.IndexOf('.') != -1)
{
MessageBox.Show("请输入正确的数字");
this.textBox1.Text = "";
e.Handled = true;
}
//第一位不能为小数点
if (e.KeyChar == (char)('.') && ((TextBox)sender).Text == "")
{
MessageBox.Show("请输入正确的数字");
this.textBox1.Text = "";
e.Handled = true;
}
//第一位是0,第二位必须为小数点
if (e.KeyChar != (char)('.') && ((TextBox)sender).Text == "0")
{
MessageBox.Show("请输入正确的数字");
this.textBox1.Text = "";
e.Handled = true;
}
//第一位是负号,第二位不能为小数点
if (((TextBox)sender).Text == "-" && e.KeyChar == (char)('.'))
{
MessageBox.Show("请输入正确的数字");
this.textBox1.Text = "";
e.Handled = true;
}
控制只能输入整数或小数(供TextBox注册KeyPress事件)#region 控制只能输入整数或小数(供TextBox注册KeyPress事件)
/**//// <summary>
/// 控制只能输入整数或小数
/// (小数位最多位4位,小数位可以自己修改)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Txb_Decimal_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
{
if(e.KeyChar == '.')
{
if ( ((TextBox)sender).Text.Trim().IndexOf('.') > -1)
e.Handled = true;
}
else
e.Handled = true;
}
else
{
if( e.KeyChar <= 31 )
{
e.Handled = false ;
}
else if( ((TextBox)sender).Text.Trim().IndexOf('.') > -1 )
{
if( ((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1 ).Length >= 4)
e.Handled = true ;
}
}
}
#endregion