只允许文本框中的特定字符 [英] Only allow specific characters in textbox

查看:16
本文介绍了只允许文本框中的特定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Visual C# 文本框中只允许某些字符?用户应该能够在文本框中输入以下字符,并且应该阻止其他所有字符:0-9、+、-、/、*、(、).

How can I only allow certain characters in a Visual C# textbox? Users should be able to input the following characters into a text box, and everything else should be blocked: 0-9, +, -, /, *, (, ).

我已使用 Google 查找此问题,但我得到的唯一解决方案是仅允许字母字符、仅数字字符或不允许某些字符.我想要的不是禁止某些字符,我想默认禁止所有字符,除了我在代码中输入的字符.

I've used Google to look up this problem, but the only solutions I'm getting are allowing only alphabetic characters, only numerical or disallowing certain characters. What I want is not disallowing certain characters, I want to disallow everything by default except the characters that I put in the code.

推荐答案

正如评论中提到的(以及我输入的另一个答案),您需要注册一个事件处理程序来捕获文本框上的 keydown 或 keypress 事件.这是因为 TextChanged 仅在 TextBox 失去焦点时触发

As mentioned in a comment (and another answer as I typed) you need to register an event handler to catch the keydown or keypress event on a text box. This is because TextChanged is only fired when the TextBox loses focus

下面的正则表达式可以让你匹配那些你想要允许的字符

The below regex lets you match those characters you want to allow

Regex regex = new Regex(@"[0-9+-/*()]");
MatchCollection matches = regex.Matches(textValue);

而这恰恰相反,会捕获不允许的字符

and this does the opposite and catches characters that aren't allowed

Regex regex = new Regex(@"[^0-9^+^-^/^*^(^)]");
MatchCollection matches = regex.Matches(textValue);

我不会假设会有一个匹配项,因为有人可以将文本粘贴到文本框中.在这种情况下捕获 textchanged

I'm not assuming there'll be a single match as someone could paste text into the textbox. in which case catch textchanged

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;
    }
}

这篇关于只允许文本框中的特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆