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

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

问题描述

我怎么能只允许在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, +, -, /, *, (, ).

我用谷歌来查找这个问题,但我得到的唯一的解决办法是只允许字母,数字只或禁止某些字符。我想是不是不允许某些字符,我希望禁止由不同的是,我把代码中的字符默认一切。

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或按键事件。这是因为框TextChanged只发射时,文本框失去焦点

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天全站免登陆