TextBox(只允许输入字母或者数字)——重写控件

实现如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PISS.View.CustomControl
{
public class LetterAndNum : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);

SetStandard(e);
}

private void SetStandard(System.Windows.Forms.KeyPressEventArgs e)
{
//只允许输入字母
Regex regex = new Regex(@"^([A-Za-z0-9]|[])+$");
MatchCollection mc = regex.Matches(e.KeyChar.ToString());
foreach (Match ma in mc)
{
e.Handled = false;
return;
}

e.Handled = true;
}
}
}

原文地址:https://www.cnblogs.com/YYkun/p/5662833.html