【C#】控制文本框(TextBox)只能输入正数,负数,小数

/* 
 *设置textBox只能输入数字(正数,负数,小数) 
 *使用了TextBox的KeyPress事件
 */  
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;  
	}
}
  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值