WinForm下的TextBox只能输入整数(可正可负)

来源:互联网 发布:txt数据导入excel 编辑:程序博客网 时间:2024/06/07 14:41

 using System.Text.RegularExpressions;

 

private string pattern = @"^[\-]?[0-9]*$";
        private string temp = String.Empty;

 private void txtInput_TextChanged(object sender, EventArgs e)
        {
            Match m = Regex.Match(this.txtInput.Text, pattern);   // 匹配正则表达式

            if (!m.Success)   // 输入的不是数字
            {
                this.txtInput.Text = temp;   // textBox内容不变

                // 将光标定位到文本框的最后
                this.txtInput.SelectionStart = this.txtInput.Text.Length;
            }
            else   // 输入的是数字
            {
                temp = this.txtInput.Text;   // 将现在textBox的值保存下来
            }
        }