如何在 Visual C# 文本框中仅允许某些字符?用户应该能够在文本框中输入以下字符,其他所有字符都应该被阻止:0-9、+、-、/、*、(、)。
我已经使用谷歌来查找这个问题,但我得到的唯一解决方案是只允许字母字符,只允许数字或不允许某些字符。我想要的不是禁止某些字符,我想默认禁止除我在代码中放入的字符之外的所有字符。
正如评论(以及我输入的另一个答案)中提到的,您需要注册一个事件处理程序来捕获文本框上的 keydown 或 keypress 事件。这是因为 TextChanged 仅在 TextBox 失去焦点时触发
下面的正则表达式可以让您匹配那些您想要允许的字符
Regex regex = new Regex(@"[0-9+\-\/\*\(\)]");
MatchCollection matches = regex.Matches(textValue);
这会起到相反的作用并捕获不允许的字符
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textValue);
我不假设会有一个匹配,因为有人可以将文本粘贴到文本框中。在这种情况下捕获文本更改
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
private void textBox1_TextChanged(object sender, EventArgs e)
{
Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textBox1.Text);
if (matches.Count > 0) {
//tell the user
}
}
并验证单键按下
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for a naughty character in the KeyDown event.
if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^\-^\/^\*^\(^\)]"))
{
// Stop the character from being entered into the control since it is illegal.
e.Handled = true;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)