控制winform文本框输入字符限制(数字或字母、长度)

使用keyPress事件效果比keydown效果要好 

private void txtDBThempLibName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Back) {
                e.Handled = false;
                return;
            }
            string pattern = @"^[a-zA-Z0-9]{0,6}$";
            if (!Regex.IsMatch(txtDBThempLibName.Text.Trim(), pattern))
            {
                MessageBox.Show("输入格式不正确,请检查:\r\n请检查输入是否为数字或字母以外的符号");
                return;
            }
            if (txtDBThempLibName.Text.Trim().Length>0)
                btnImport.Enabled = true;
            else
                btnImport.Enabled = false;
            if (txtDBThempLibName.Text.Length >= 6) e.Handled = true;
        }

你可能感兴趣的:(WinForm)