textbox限制输入为数字

来源:互联网 发布:和程序员男友滚床单 编辑:程序博客网 时间:2024/05/27 20:44

如题

1、如果只是限制为数字,则参考论坛的思路,用正直表达式和TextChanged方法,代码入下:

private void TextBox1_TextChanged(object sender, System.EventArgs e) {
            int curr = this.TextBox1.SelectionStart;
            System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex("[^0-9]+");
            this.TextBox1.Text = rg.Replace(this.TextBox1.Text, "");
            if (this.TextBox1.SelectionStart == 0)
            {
                this.TextBox1.SelectionStart = 0;
            }
            else {
                this.TextBox1.SelectionStart = curr;
            }
        }


2、但是要求文本框输入的不但只是数字,而且开头不能为零,这里会用KeyPress方法实现,代码如下:

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e) {
            //过滤开头为零的输入
            if (TextBox1.Text.Length == 0 && e.KeyChar.ToString() == "0")
            {
                e.Handled = true;
            }
            //过滤不是数字的输入
            if (e.KeyChar != 8 && !char.IsNumber(e.KeyChar))
            {
                e.Handled = true;
            }
        }


当然,第一种方法也能实现第二种功能,如果有想法,请留言!!!

原创粉丝点击