C#限制文本框只能输入指定的类型(汉字、数字)

现在已经开始机房一段时间了,敲到添加用户的时候,想着学号只能是数字,姓名只能是汉字,那么如何实现?在这里用到了正则表达式……

指定文本框是汉字

首先要引用程序集:

using System.Text.RegularExpressions;

代码:

 Regex rg = new Regex("^[\u4e00-\u9fa5]$");//正则表达式
            if (!rg.IsMatch(e.KeyChar.ToString()) && e.KeyChar != '\b') //'\b'是退格键 
            {
                e.Handled = true;
            }

指定文本是数字 

private void textBox5_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;//handle为已处理
            }
        }

 

Guess you like

Origin blog.csdn.net/weixin_45309155/article/details/116093157