C#winform怎样禁止非法字符的输入?

时间:2026-02-13 06:15:43

1、打开visual studio2010,添加“解决方案”--“新建项目”

C#winform怎样禁止非法字符的输入?

2、窗体布局如下:三个Lable控件,三个TextBoxe控件,两个Button控件

C#winform怎样禁止非法字符的输入?

3、关键步骤:

1、选中用户名输入的TextBoxe控件,

2、选择属性--事件--选择KeyPress事件,双击

C#winform怎样禁止非法字符的输入?

4、在弹出的代码编辑窗,输入下列代码:

namespace 经验

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

        {

//此为只能输入字母

            if (e.KeyChar < 'A' || e.KeyChar > 'Z' && e.KeyChar < 'a' || e.KeyChar > 'z')

            {

                e.Handled = true;

            }

//此为退格键可以输入

            if (e.KeyChar == 8)

            {

                e.Handled = false;

            }

        }

    }

}

C#winform怎样禁止非法字符的输入?

5、ok!在用户名栏里,只能输入字母了。

C#winform怎样禁止非法字符的输入?

© 2026 途途旅游
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com