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

C#中TextBox只允许输入数字或者带负号或者小数点

2010-10-15 20:13 190 查看
(1)新建一个windows应用程序,将其命名为HardlyEnableFigure

(2)在窗体中添加TextBox控件,用于输入要验证的数字

(3)主要代码:

using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace HardlyEnableFigure
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ((!char.IsDigit(e.KeyChar) && e.KeyChar != 8) && e.KeyChar != 13)
{
//弹出信息提示
MessageBox.Show("商品数量只能是数字", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
e.Handled = true;//表示已经处理过keypress事件

}
}
}
}

//输入为负号时,只能输入一次且只能输入一次
if (e.KeyChar == 45 && (((TextBox)sender).SelectionStart != 0 || ((TextBox)sender).Text.IndexOf("-") >= 0)) e.Handled = true;
//允许输入负号
if (e.KeyChar == 46 && ((TextBox)sender).Text.IndexOf(".") >= 0) e.Handled = true;
//允许输入小数点
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: